blob: f1d5d166a808c43470635d7a7efd3323d8778401 [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
Ruben Brunkd1176ef2014-02-21 10:51:38 -08002 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Mathias Agopian65ab4712010-07-14 17:59:35 -070016
17#define LOG_TAG "CameraService"
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -070018#define ATRACE_TAG ATRACE_TAG_CAMERA
Iliyan Malchev8951a972011-04-14 16:55:59 -070019//#define LOG_NDEBUG 0
Mathias Agopian65ab4712010-07-14 17:59:35 -070020
Ruben Brunkcc776712015-02-17 20:18:47 -080021#include <algorithm>
22#include <climits>
Mathias Agopian65ab4712010-07-14 17:59:35 -070023#include <stdio.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080024#include <cstring>
25#include <ctime>
26#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070027#include <sys/types.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080028#include <inttypes.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070029#include <pthread.h>
30
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080031#include <android/hardware/ICamera.h>
32#include <android/hardware/ICameraClient.h>
33
Alex Deymo9c2a2c22016-08-25 11:59:14 -070034#include <android-base/macros.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080035#include <android-base/parseint.h>
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070036#include <android-base/stringprintf.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080037#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080038#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070039#include <binder/IPCThreadState.h>
40#include <binder/IServiceManager.h>
41#include <binder/MemoryBase.h>
42#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080043#include <binder/PermissionController.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080044#include <binder/ProcessInfoService.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080045#include <binder/IResultReceiver.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070046#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070047#include <cutils/properties.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080048#include <cutils/misc.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080049#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070050#include <hardware/hardware.h>
Jayant Chowdharybe543d42018-08-15 13:16:14 -070051#include "hidl/HidlCameraService.h"
52#include <hidl/HidlTransportSupport.h>
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -080053#include <hwbinder/IPCThreadState.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070054#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070055#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080056#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070057#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070058#include <mediautils/BatteryNotifier.h>
Michael Grooverd1d435a2018-12-18 17:39:42 -080059#include <sensorprivacy/SensorPrivacyManager.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) {
460 logDeviceRemoved(id, String8::format("Device %s-%s availability changed from %d to %d",
461 id.string(), physicalId.string(),
462 newStatus != StatusInternal::PRESENT,
463 newStatus == StatusInternal::PRESENT));
464
465 String16 id16(id), physicalId16(physicalId);
466 Mutex::Autolock lock(mStatusListenerLock);
467 for (auto& listener : mListenerList) {
468 listener->getListener()->onPhysicalCameraStatusChanged(mapToInterface(newStatus),
469 id16, physicalId16);
470 }
471 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700472}
473
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800474void CameraService::disconnectClient(const String8& id, sp<BasicClient> clientToDisconnect) {
475 if (clientToDisconnect.get() != nullptr) {
476 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
477 __FUNCTION__, id.string());
478 // Notify the client of disconnection
479 clientToDisconnect->notifyError(
480 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
481 CaptureResultExtras{});
482 // Ensure not in binder RPC so client disconnect PID checks work correctly
483 LOG_ALWAYS_FATAL_IF(CameraThreadState::getCallingPid() != getpid(),
484 "onDeviceStatusChanged must be called from the camera service process!");
485 clientToDisconnect->disconnect();
486 }
487}
488
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800489void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800490 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800491 Mutex::Autolock al(mTorchStatusMutex);
492 onTorchStatusChangedLocked(cameraId, newStatus);
493}
494
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800495void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800496 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800497 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
498 __FUNCTION__, cameraId.string(), newStatus);
499
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800500 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800501 status_t res = getTorchStatusLocked(cameraId, &status);
502 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700503 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
504 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800505 return;
506 }
507 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800508 return;
509 }
510
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800511 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800512 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800513 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
514 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800515 return;
516 }
517
Ruben Brunkcc776712015-02-17 20:18:47 -0800518 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700519 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700520 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700521 auto iter = mTorchUidMap.find(cameraId);
522 if (iter != mTorchUidMap.end()) {
523 int oldUid = iter->second.second;
524 int newUid = iter->second.first;
525 BatteryNotifier& notifier(BatteryNotifier::getInstance());
526 if (oldUid != newUid) {
527 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800528 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700529 notifier.noteFlashlightOff(cameraId, oldUid);
530 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800531 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700532 notifier.noteFlashlightOn(cameraId, newUid);
533 }
534 iter->second.second = newUid;
535 } else {
536 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800537 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700538 notifier.noteFlashlightOn(cameraId, oldUid);
539 } else {
540 notifier.noteFlashlightOff(cameraId, oldUid);
541 }
542 }
543 }
544 }
545
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800546 broadcastTorchModeStatus(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800547}
548
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700549static bool hasPermissionsForSystemCamera(int callingPid, int callingUid) {
550 return checkPermission(sSystemCameraPermission, callingPid, callingUid) &&
551 checkPermission(sCameraPermission, callingPid, callingUid);
552}
553
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800554Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700555 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100556 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700557 bool hasSystemCameraPermissions =
558 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
559 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700560 switch (type) {
561 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700562 if (hasSystemCameraPermissions) {
563 *numCameras = static_cast<int>(mNormalDeviceIds.size());
564 } else {
565 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
566 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800567 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700568 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700569 if (hasSystemCameraPermissions) {
570 *numCameras = mNumberOfCameras;
571 } else {
572 *numCameras = mNumberOfCamerasWithoutSystemCamera;
573 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800574 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700575 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800576 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700577 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800578 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
579 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700580 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800581 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700582}
583
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800584Status CameraService::getCameraInfo(int cameraId,
585 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700586 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100587 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700588 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
589 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
590 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
591 "characteristics for system only device %s: ", cameraIdStr.c_str());
592 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100593
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800594 if (!mInitialized) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800595 return STATUS_ERROR(ERROR_DISCONNECTED,
596 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700597 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700598 bool hasSystemCameraPermissions =
599 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
600 CameraThreadState::getCallingUid());
601 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
602 if (hasSystemCameraPermissions) {
603 cameraIdBound = mNumberOfCameras;
604 }
605 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800606 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
607 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700608 }
609
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800610 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800611 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700612 cameraIdStr.c_str(), cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100613 if (err != OK) {
614 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
615 "Error retrieving camera info from device %d: %s (%d)", cameraId,
616 strerror(-err), err);
Ruben Brunkcc776712015-02-17 20:18:47 -0800617 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100618
Ruben Brunkcc776712015-02-17 20:18:47 -0800619 return ret;
620}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700621
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800622std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700623 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
624 auto callingPid = CameraThreadState::getCallingPid();
625 auto callingUid = CameraThreadState::getCallingUid();
626 if (checkPermission(sSystemCameraPermission, callingPid, callingUid) ||
627 getpid() == callingPid) {
628 deviceIds = &mNormalDeviceIds;
629 }
630 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800631 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700632 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800633 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800634 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800635
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700636 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800637}
638
639String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
640 Mutex::Autolock lock(mServiceLock);
641 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800642}
643
644Status CameraService::getCameraCharacteristics(const String16& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800645 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700646 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700647 if (!cameraInfo) {
648 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800649 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700650 }
651
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800652 if (!mInitialized) {
653 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800654 return STATUS_ERROR(ERROR_DISCONNECTED,
655 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700656 }
657
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700658 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
659 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
660 "characteristics for system only device %s: ", String8(cameraId).string());
661 }
662
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800663 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800664
Emilian Peevf53f66e2017-04-11 14:29:43 +0100665 status_t res = mCameraProviderManager->getCameraCharacteristics(
666 String8(cameraId).string(), cameraInfo);
667 if (res != OK) {
668 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
669 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
670 strerror(-res), res);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700671 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700672 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
673 if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
674 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
675 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
676 "for device %s", String8(cameraId).string());
677 }
Jayant Chowdhary12361932018-08-27 14:46:13 -0700678 int callingPid = CameraThreadState::getCallingPid();
679 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100680 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700681 // If it's not calling from cameraserver, check the permission only if
682 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
683 // it would've already been checked in shouldRejectSystemCameraConnection.
Emilian Peeve20c6372018-08-14 18:45:53 +0100684 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700685 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700686 !checkPermission(sCameraPermission, callingPid, callingUid)) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100687 res = cameraInfo->removePermissionEntries(
688 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
689 &tagsRemoved);
690 if (res != OK) {
691 cameraInfo->clear();
692 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
693 " characteristics needing camera permission for device %s: %s (%d)",
694 String8(cameraId).string(), strerror(-res), res);
695 }
696 }
697
698 if (!tagsRemoved.empty()) {
699 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
700 tagsRemoved.data(), tagsRemoved.size());
701 if (res != OK) {
702 cameraInfo->clear();
703 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
704 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
705 strerror(-res), res);
706 }
707 }
708
Zhijun He2b59be82013-09-25 10:14:30 -0700709 return ret;
710}
711
Ruben Brunkcc776712015-02-17 20:18:47 -0800712String8 CameraService::getFormattedCurrentTime() {
713 time_t now = time(nullptr);
714 char formattedTime[64];
715 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
716 return String8(formattedTime);
717}
718
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800719Status CameraService::getCameraVendorTagDescriptor(
720 /*out*/
721 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700722 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800723 if (!mInitialized) {
724 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800725 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800726 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800727 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
728 if (globalDescriptor != nullptr) {
729 *desc = *(globalDescriptor.get());
730 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800731 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800732}
733
Emilian Peev71c73a22017-03-21 16:35:51 +0000734Status CameraService::getCameraVendorTagCache(
735 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
736 ATRACE_CALL();
737 if (!mInitialized) {
738 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
739 return STATUS_ERROR(ERROR_DISCONNECTED,
740 "Camera subsystem not available");
741 }
742 sp<VendorTagDescriptorCache> globalCache =
743 VendorTagDescriptorCache::getGlobalVendorTagCache();
744 if (globalCache != nullptr) {
745 *cache = *(globalCache.get());
746 }
747 return Status::ok();
748}
749
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800750int CameraService::getDeviceVersion(const String8& cameraId, int* facing) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700751 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800752
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800753 int deviceVersion = 0;
754
Emilian Peevf53f66e2017-04-11 14:29:43 +0100755 status_t res;
756 hardware::hidl_version maxVersion{0,0};
757 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
758 &maxVersion);
759 if (res != OK) return -1;
760 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800761
Emilian Peevf53f66e2017-04-11 14:29:43 +0100762 hardware::CameraInfo info;
763 if (facing) {
764 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800765 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100766 *facing = info.facing;
Igor Murashkin634a5152013-02-20 17:15:11 -0800767 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100768
Igor Murashkin634a5152013-02-20 17:15:11 -0800769 return deviceVersion;
770}
771
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800772Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700773 switch(err) {
774 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800775 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800776 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800777 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
778 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800779 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800780 return STATUS_ERROR(ERROR_DISCONNECTED,
781 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700782 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800783 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
784 "Camera HAL encountered error %d: %s",
785 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700786 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800787}
788
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800789Status CameraService::makeClient(const sp<CameraService>& cameraService,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800790 const sp<IInterface>& cameraCb, const String16& packageName,
791 const std::unique_ptr<String16>& featureId, const String8& cameraId, int api1CameraId,
792 int facing, int clientPid, uid_t clientUid, int servicePid, int halVersion,
793 int deviceVersion, apiLevel effectiveApiLevel,
Ruben Brunkcc776712015-02-17 20:18:47 -0800794 /*out*/sp<BasicClient>* client) {
795
Ruben Brunkcc776712015-02-17 20:18:47 -0800796 if (halVersion < 0 || halVersion == deviceVersion) {
797 // Default path: HAL version is unspecified by caller, create CameraClient
798 // based on device version reported by the HAL.
799 switch(deviceVersion) {
800 case CAMERA_DEVICE_API_VERSION_1_0:
801 if (effectiveApiLevel == API_1) { // Camera1 API route
802 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800803 *client = new CameraClient(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800804 api1CameraId, facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700805 getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800806 } else { // Camera2 API route
807 ALOGW("Camera using old HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800808 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800809 "Camera device \"%s\" HAL version %d does not support camera2 API",
810 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800811 }
812 break;
Ruben Brunkcc776712015-02-17 20:18:47 -0800813 case CAMERA_DEVICE_API_VERSION_3_0:
814 case CAMERA_DEVICE_API_VERSION_3_1:
815 case CAMERA_DEVICE_API_VERSION_3_2:
816 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -0700817 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -0700818 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -0800819 case CAMERA_DEVICE_API_VERSION_3_6:
Ruben Brunkcc776712015-02-17 20:18:47 -0800820 if (effectiveApiLevel == API_1) { // Camera1 API route
821 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800822 *client = new Camera2Client(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800823 cameraId, api1CameraId,
824 facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700825 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800826 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800827 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
828 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800829 *client = new CameraDeviceClient(cameraService, tmp, packageName, featureId,
830 cameraId, facing, clientPid, clientUid, servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800831 }
832 break;
833 default:
834 // Should not be reachable
835 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800836 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800837 "Camera device \"%s\" has unknown HAL version %d",
838 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800839 }
840 } else {
841 // A particular HAL version is requested by caller. Create CameraClient
842 // based on the requested HAL version.
843 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
844 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
845 // Only support higher HAL version device opened as HAL1.0 device.
846 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800847 *client = new CameraClient(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800848 api1CameraId, facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700849 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800850 } else {
851 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
852 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
853 " opened as HAL %x device", halVersion, deviceVersion,
854 CAMERA_DEVICE_API_VERSION_1_0);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800855 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800856 "Camera device \"%s\" (HAL version %d) cannot be opened as HAL version %d",
857 cameraId.string(), deviceVersion, halVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800858 }
859 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800860 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800861}
862
Ruben Brunk6267b532015-04-30 17:44:07 -0700863String8 CameraService::toString(std::set<userid_t> intSet) {
864 String8 s("");
865 bool first = true;
866 for (userid_t i : intSet) {
867 if (first) {
868 s.appendFormat("%d", i);
869 first = false;
870 } else {
871 s.appendFormat(", %d", i);
872 }
873 }
874 return s;
875}
876
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800877int32_t CameraService::mapToInterface(TorchModeStatus status) {
878 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
879 switch (status) {
880 case TorchModeStatus::NOT_AVAILABLE:
881 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
882 break;
883 case TorchModeStatus::AVAILABLE_OFF:
884 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
885 break;
886 case TorchModeStatus::AVAILABLE_ON:
887 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
888 break;
889 default:
890 ALOGW("Unknown new flash status: %d", status);
891 }
892 return serviceStatus;
893}
894
895CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
896 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
897 switch (status) {
898 case CameraDeviceStatus::NOT_PRESENT:
899 serviceStatus = StatusInternal::NOT_PRESENT;
900 break;
901 case CameraDeviceStatus::PRESENT:
902 serviceStatus = StatusInternal::PRESENT;
903 break;
904 case CameraDeviceStatus::ENUMERATING:
905 serviceStatus = StatusInternal::ENUMERATING;
906 break;
907 default:
908 ALOGW("Unknown new HAL device status: %d", status);
909 }
910 return serviceStatus;
911}
912
913int32_t CameraService::mapToInterface(StatusInternal status) {
914 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
915 switch (status) {
916 case StatusInternal::NOT_PRESENT:
917 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
918 break;
919 case StatusInternal::PRESENT:
920 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
921 break;
922 case StatusInternal::ENUMERATING:
923 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
924 break;
925 case StatusInternal::NOT_AVAILABLE:
926 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
927 break;
928 case StatusInternal::UNKNOWN:
929 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
930 break;
931 default:
932 ALOGW("Unknown new internal device status: %d", status);
933 }
934 return serviceStatus;
935}
936
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800937Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -0700938 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700939
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800940 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -0800941 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800942 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800943 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800944 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800945 sp<ICameraClient>{nullptr}, id, cameraId,
946 static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800947 internalPackageName, std::unique_ptr<String16>(), uid, USE_CALLING_PID,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700948 API_1, /*shimUpdateOnly*/ true, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800949 ).isOk()) {
950 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -0700951 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800952 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700953}
954
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800955Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -0700956 /*out*/
957 CameraParameters* parameters) {
958
959 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
960
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800961 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -0700962
963 if (parameters == NULL) {
964 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800965 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700966 }
967
Ruben Brunkcc776712015-02-17 20:18:47 -0800968 String8 id = String8::format("%d", cameraId);
969
970 // Check if we already have parameters
971 {
972 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700973 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800974 auto cameraState = getCameraState(id);
975 if (cameraState == nullptr) {
976 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800977 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
978 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800979 }
980 CameraParameters p = cameraState->getShimParams();
981 if (!p.isEmpty()) {
982 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800983 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700984 }
985 }
986
Jayant Chowdhary12361932018-08-27 14:46:13 -0700987 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -0800988 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -0700989 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800990 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800991 // Error already logged by callee
992 return ret;
993 }
994
995 // Check for parameters again
996 {
997 // Scope for service lock
998 Mutex::Autolock lock(mServiceLock);
999 auto cameraState = getCameraState(id);
1000 if (cameraState == nullptr) {
1001 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001002 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1003 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001004 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001005 CameraParameters p = cameraState->getShimParams();
1006 if (!p.isEmpty()) {
1007 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001008 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001009 }
1010 }
1011
Ruben Brunkcc776712015-02-17 20:18:47 -08001012 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1013 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001014 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001015}
1016
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001017// Can camera service trust the caller based on the calling UID?
1018static bool isTrustedCallingUid(uid_t uid) {
1019 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001020 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001021 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001022 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001023 return true;
1024 default:
1025 return false;
1026 }
1027}
1028
Nicholas Sauera3620332019-04-03 14:05:17 -07001029static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1030 PermissionController pc;
1031 uid = pc.getPackageUid(packageName, 0);
1032 if (uid <= 0) {
1033 ALOGE("Unknown package: '%s'", String8(packageName).string());
1034 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1035 return BAD_VALUE;
1036 }
1037
1038 if (userId < 0) {
1039 ALOGE("Invalid user: %d", userId);
1040 dprintf(err, "Invalid user: %d\n", userId);
1041 return BAD_VALUE;
1042 }
1043
1044 uid = multiuser_get_uid(userId, uid);
1045 return NO_ERROR;
1046}
1047
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001048Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001049 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1050 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001051
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001052#ifdef __BRILLO__
1053 UNUSED(clientName8);
1054 UNUSED(clientUid);
1055 UNUSED(clientPid);
1056 UNUSED(originalClientPid);
1057#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001058 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1059 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001060 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001061 return allowed;
1062 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001063#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001064
Jayant Chowdhary12361932018-08-27 14:46:13 -07001065 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001066
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001067 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001068 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1069 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001070 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1071 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001072 }
1073
Ruben Brunkcc776712015-02-17 20:18:47 -08001074 if (getCameraState(cameraId) == nullptr) {
1075 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1076 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001077 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1078 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001079 }
1080
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001081 status_t err = checkIfDeviceIsUsable(cameraId);
1082 if (err != NO_ERROR) {
1083 switch(err) {
1084 case -ENODEV:
1085 case -EBUSY:
1086 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1087 "No camera device with ID \"%s\" currently available", cameraId.string());
1088 default:
1089 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1090 "Unknown error connecting to ID \"%s\"", cameraId.string());
1091 }
1092 }
1093 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001094}
1095
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001096Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001097 const String8& clientName8, int& clientUid, int& clientPid,
1098 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001099 int callingPid = CameraThreadState::getCallingPid();
1100 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001101
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001102 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001103 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001104 clientUid = callingUid;
1105 } else if (!isTrustedCallingUid(callingUid)) {
1106 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1107 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001108 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1109 "Untrusted caller (calling PID %d, UID %d) trying to "
1110 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1111 callingPid, callingUid, cameraId.string(),
1112 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001113 }
1114
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001115 // Check if we can trust clientPid
1116 if (clientPid == USE_CALLING_PID) {
1117 clientPid = callingPid;
1118 } else if (!isTrustedCallingUid(callingUid)) {
1119 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1120 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001121 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1122 "Untrusted caller (calling PID %d, UID %d) trying to "
1123 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1124 callingPid, callingUid, cameraId.string(),
1125 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001126 }
1127
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001128 if (shouldRejectSystemCameraConnection(cameraId)) {
1129 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1130 cameraId.c_str());
1131 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1132 "available", cameraId.string());
1133 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001134 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1135 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1136 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1137 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1138 "found while trying to query device kind", cameraId.string());
1139
1140 }
1141
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001142 // If it's not calling from cameraserver, check the permission if the
1143 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1144 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001145 if (callingPid != getpid() &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001146 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001147 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001148 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001149 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1150 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1151 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001152 }
1153
Svet Ganova453d0d2018-01-11 15:37:58 -08001154 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001155 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001156 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001157 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1158 clientPid, clientUid);
1159 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001160 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1161 "calling UID %d proc state %" PRId32 ")",
1162 clientName8.string(), clientUid, clientPid, cameraId.string(),
1163 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001164 }
1165
Michael Grooverd1d435a2018-12-18 17:39:42 -08001166 // If sensor privacy is enabled then prevent access to the camera
1167 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1168 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1169 return STATUS_ERROR_FMT(ERROR_DISABLED,
1170 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1171 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1172 }
1173
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001174 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1175 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001176 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001177 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001178
Ruben Brunk6267b532015-04-30 17:44:07 -07001179 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001180
Ruben Brunka8ca9152015-04-07 14:23:40 -07001181 // Only allow clients who are being used by the current foreground device user, unless calling
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001182 // from our own process OR the caller is using the cameraserver's HIDL interface.
1183 if (!hardware::IPCThreadState::self()->isServingCall() && callingPid != getpid() &&
1184 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001185 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1186 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1187 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001188 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1189 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1190 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001191 }
1192
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001193 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001194}
1195
1196status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1197 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001198 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001199 if (cameraState == nullptr) {
1200 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1201 cameraId.string());
1202 return -ENODEV;
1203 }
1204
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001205 StatusInternal currentStatus = cameraState->getStatus();
1206 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001207 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1208 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001209 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001210 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001211 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1212 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001213 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001214 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001215
Ruben Brunkcc776712015-02-17 20:18:47 -08001216 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001217}
1218
Ruben Brunkcc776712015-02-17 20:18:47 -08001219void CameraService::finishConnectLocked(const sp<BasicClient>& client,
1220 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001221
Ruben Brunkcc776712015-02-17 20:18:47 -08001222 // Make a descriptor for the incoming client
1223 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
1224 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1225
1226 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1227 String8(client->getPackageName()));
1228
1229 if (evicted.size() > 0) {
1230 // This should never happen - clients should already have been removed in disconnect
1231 for (auto& i : evicted) {
1232 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1233 __FUNCTION__, i->getKey().string());
1234 }
1235
1236 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1237 __FUNCTION__);
1238 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001239
1240 // And register a death notification for the client callback. Do
1241 // this last to avoid Binder policy where a nested Binder
1242 // transaction might be pre-empted to service the client death
1243 // notification if the client process dies before linkToDeath is
1244 // invoked.
1245 sp<IBinder> remoteCallback = client->getRemote();
1246 if (remoteCallback != nullptr) {
1247 remoteCallback->linkToDeath(this);
1248 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001249}
1250
1251status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1252 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
1253 /*out*/
1254 sp<BasicClient>* client,
1255 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001256 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001257 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001258 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001259 DescriptorPtr clientDescriptor;
1260 {
1261 if (effectiveApiLevel == API_1) {
1262 // If we are using API1, any existing client for this camera ID with the same remote
1263 // should be returned rather than evicted to allow MediaRecorder to work properly.
1264
1265 auto current = mActiveClientManager.get(cameraId);
1266 if (current != nullptr) {
1267 auto clientSp = current->getValue();
1268 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001269 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1270 ALOGW("CameraService connect called from same client, but with a different"
1271 " API level, evicting prior client...");
1272 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001273 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001274 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001275 *client = clientSp;
1276 return NO_ERROR;
1277 }
1278 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001279 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001280 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001281
Ruben Brunkcc776712015-02-17 20:18:47 -08001282 // Get current active client PIDs
1283 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1284 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001285
Emilian Peev8131a262017-02-01 12:33:43 +00001286 std::vector<int> priorityScores(ownerPids.size());
1287 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001288
Emilian Peev8131a262017-02-01 12:33:43 +00001289 // Get priority scores of all active PIDs
1290 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1291 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1292 /*out*/&priorityScores[0]);
1293 if (err != OK) {
1294 ALOGE("%s: Priority score query failed: %d",
1295 __FUNCTION__, err);
1296 return err;
1297 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001298
Ruben Brunkcc776712015-02-17 20:18:47 -08001299 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001300 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001301 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001302 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001303 resource_policy::ClientPriority(priorityScores[i], states[i],
1304 /* isVendorClient won't get copied over*/ false));
Ruben Brunkcc776712015-02-17 20:18:47 -08001305 }
1306 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001307
Ruben Brunkcc776712015-02-17 20:18:47 -08001308 // Get state for the given cameraId
1309 auto state = getCameraState(cameraId);
1310 if (state == nullptr) {
1311 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1312 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001313 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001314 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001315 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001316
1317 // Make descriptor for incoming client
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001318 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001319 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1320 state->getConflicting(),
Emilian Peev8131a262017-02-01 12:33:43 +00001321 priorityScores[priorityScores.size() - 1],
1322 clientPid,
1323 states[states.size() - 1]);
Ruben Brunkcc776712015-02-17 20:18:47 -08001324
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001325 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1326
Ruben Brunkcc776712015-02-17 20:18:47 -08001327 // Find clients that would be evicted
1328 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1329
1330 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1331 // background, so we cannot do evictions
1332 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1333 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1334 " priority).", clientPid);
1335
1336 sp<BasicClient> clientSp = clientDescriptor->getValue();
1337 String8 curTime = getFormattedCurrentTime();
1338 auto incompatibleClients =
1339 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1340
1341 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001342 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001343 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001344 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001345
1346 for (auto& i : incompatibleClients) {
1347 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001348 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1349 i->getKey().string(),
1350 String8{i->getValue()->getPackageName()}.string(),
1351 i->getOwnerId(), i->getPriority().getScore(),
1352 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001353 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001354 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001355 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001356 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001357 }
1358
1359 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001360 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001361 mEventLog.add(msg);
1362
1363 return -EBUSY;
1364 }
1365
1366 for (auto& i : evicted) {
1367 sp<BasicClient> clientSp = i->getValue();
1368 if (clientSp.get() == nullptr) {
1369 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1370
1371 // TODO: Remove this
1372 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1373 __FUNCTION__);
1374 mActiveClientManager.remove(i);
1375 continue;
1376 }
1377
1378 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1379 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001380 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001381
Ruben Brunkcc776712015-02-17 20:18:47 -08001382 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001383 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001384 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1385 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001386 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001387 i->getOwnerId(), i->getPriority().getScore(),
1388 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001389 packageName.string(), clientPid, clientPriority.getScore(),
1390 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001391
1392 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001393 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001394 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001395 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001396 }
1397
Ruben Brunkcc776712015-02-17 20:18:47 -08001398 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1399 // other clients from connecting in mServiceLockWrapper if held
1400 mServiceLock.unlock();
1401
1402 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001403 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001404
1405 // Destroy evicted clients
1406 for (auto& i : evictedClients) {
1407 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001408 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001409 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001410
Jayant Chowdhary12361932018-08-27 14:46:13 -07001411 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001412
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001413 for (const auto& i : evictedClients) {
1414 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1415 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1416 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1417 if (ret == TIMED_OUT) {
1418 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1419 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1420 mActiveClientManager.toString().string());
1421 return -EBUSY;
1422 }
1423 if (ret != NO_ERROR) {
1424 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1425 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1426 ret, mActiveClientManager.toString().string());
1427 return ret;
1428 }
1429 }
1430
1431 evictedClients.clear();
1432
Ruben Brunkcc776712015-02-17 20:18:47 -08001433 // Once clients have been disconnected, relock
1434 mServiceLock.lock();
1435
1436 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1437 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1438 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001439 }
1440
Ruben Brunkcc776712015-02-17 20:18:47 -08001441 *partial = clientDescriptor;
1442 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001443}
1444
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001445Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001446 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001447 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001448 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001449 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001450 int clientPid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001451 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001452 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001453
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001454 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001455 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001456
1457 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001458 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001459 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001460 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, std::unique_ptr<String16>(),
1461 clientUid, clientPid, API_1, /*shimUpdateOnly*/ false, /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001462
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001463 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001464 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001465 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001466 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001467 }
1468
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001469 *device = client;
1470 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001471}
1472
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001473Status CameraService::connectLegacy(
Zhijun Heb10cdad2014-06-16 16:38:35 -07001474 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001475 int api1CameraId, int halVersion,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001476 const String16& clientPackageName,
Zhijun Heb10cdad2014-06-16 16:38:35 -07001477 int clientUid,
1478 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001479 sp<ICamera>* device) {
Zhijun Heb10cdad2014-06-16 16:38:35 -07001480
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001481 ATRACE_CALL();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001482 String8 id = cameraIdIntToStr(api1CameraId);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001483
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001484 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001485 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001486 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId, halVersion,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001487 clientPackageName, std::unique_ptr<String16>(), clientUid, USE_CALLING_PID, API_1,
1488 /*shimUpdateOnly*/ false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001489
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001490 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001491 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001492 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001493 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001494 }
1495
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001496 *device = client;
1497 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001498}
1499
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001500bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1501 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001502 // If the client is not a vendor client, don't add listener if
1503 // a) the camera is a publicly hidden secure camera OR
1504 // b) the camera is a system only camera and the client doesn't
1505 // have android.permission.SYSTEM_CAMERA permissions.
1506 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1507 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1508 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001509 return true;
1510 }
1511 return false;
1512}
1513
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001514bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1515 // Rules for rejection:
1516 // 1) If cameraserver tries to access this camera device, accept the
1517 // connection.
1518 // 2) The camera device is a publicly hidden secure camera device AND some
1519 // component is trying to access it on a non-hwbinder thread (generally a non HAL client),
1520 // reject it.
1521 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1522 // and the serving thread is a non hwbinder thread, the client must have
1523 // android.permission.SYSTEM_CAMERA permissions to connect.
1524
1525 int cPid = CameraThreadState::getCallingPid();
1526 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001527 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1528 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
1529 ALOGE("%s: Invalid camera id %s, ", __FUNCTION__, cameraId.c_str());
1530 return true;
1531 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001532
1533 // (1) Cameraserver trying to connect, accept.
1534 if (CameraThreadState::getCallingPid() == getpid()) {
1535 return false;
1536 }
1537 // (2)
1538 if (!hardware::IPCThreadState::self()->isServingCall() &&
1539 systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
1540 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1541 return true;
1542 }
1543 // (3) Here we only check for permissions if it is a system only camera device. This is since
1544 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1545 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1546 // same behavior for system camera devices.
1547 if (!hardware::IPCThreadState::self()->isServingCall() &&
1548 systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1549 !hasPermissionsForSystemCamera(cPid, cUid)) {
1550 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1551 cameraId.c_str());
1552 return true;
1553 }
1554
1555 return false;
1556}
1557
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001558Status CameraService::connectDevice(
1559 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001560 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001561 const String16& clientPackageName,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001562 const std::unique_ptr<String16>& clientFeatureId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001563 int clientUid,
1564 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001565 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001566
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001567 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001568 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001569 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001570 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001571 String16 clientPackageNameAdj = clientPackageName;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001572
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001573 if (hardware::IPCThreadState::self()->isServingCall()) {
1574 std::string vendorClient =
1575 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1576 clientPackageNameAdj = String16(vendorClient.c_str());
1577 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001578 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001579 /*api1CameraId*/-1,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001580 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageNameAdj, clientFeatureId,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001581 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001582
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001583 if(!ret.isOk()) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001584 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageNameAdj),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001585 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001586 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001587 }
1588
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001589 *device = client;
1590 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001591}
1592
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001593template<class CALLBACK, class CLIENT>
1594Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001595 int api1CameraId, int halVersion, const String16& clientPackageName,
1596 const std::unique_ptr<String16>& clientFeatureId, int clientUid, int clientPid,
1597 apiLevel effectiveApiLevel, bool shimUpdateOnly,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001598 /*out*/sp<CLIENT>& device) {
1599 binder::Status ret = binder::Status::ok();
1600
1601 String8 clientName8(clientPackageName);
1602
1603 int originalClientPid = 0;
1604
1605 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) for HAL version %s and "
1606 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
1607 (halVersion == -1) ? "default" : std::to_string(halVersion).c_str(),
1608 static_cast<int>(effectiveApiLevel));
1609
1610 sp<CLIENT> client = nullptr;
1611 {
1612 // Acquire mServiceLock and prevent other clients from connecting
1613 std::unique_ptr<AutoConditionLock> lock =
1614 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1615
1616 if (lock == nullptr) {
1617 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1618 , clientPid);
1619 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1620 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1621 cameraId.string(), clientName8.string(), clientPid);
1622 }
1623
1624 // Enforce client permissions and do basic sanity checks
1625 if(!(ret = validateConnectLocked(cameraId, clientName8,
1626 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1627 return ret;
1628 }
1629
1630 // Check the shim parameters after acquiring lock, if they have already been updated and
1631 // we were doing a shim update, return immediately
1632 if (shimUpdateOnly) {
1633 auto cameraState = getCameraState(cameraId);
1634 if (cameraState != nullptr) {
1635 if (!cameraState->getShimParams().isEmpty()) return ret;
1636 }
1637 }
1638
1639 status_t err;
1640
1641 sp<BasicClient> clientTmp = nullptr;
1642 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1643 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
1644 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
1645 /*out*/&partial)) != NO_ERROR) {
1646 switch (err) {
1647 case -ENODEV:
1648 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1649 "No camera device with ID \"%s\" currently available",
1650 cameraId.string());
1651 case -EBUSY:
1652 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1653 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1654 cameraId.string());
1655 default:
1656 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1657 "Unexpected error %s (%d) opening camera \"%s\"",
1658 strerror(-err), err, cameraId.string());
1659 }
1660 }
1661
1662 if (clientTmp.get() != nullptr) {
1663 // Handle special case for API1 MediaRecorder where the existing client is returned
1664 device = static_cast<CLIENT*>(clientTmp.get());
1665 return ret;
1666 }
1667
1668 // give flashlight a chance to close devices if necessary.
1669 mFlashlight->prepareDeviceOpen(cameraId);
1670
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001671 int facing = -1;
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001672 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001673 if (facing == -1) {
1674 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1675 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1676 "Unable to get camera device \"%s\" facing", cameraId.string());
1677 }
1678
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001679 sp<BasicClient> tmp = nullptr;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001680 if(!(ret = makeClient(this, cameraCb, clientPackageName, clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001681 cameraId, api1CameraId, facing,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001682 clientPid, clientUid, getpid(),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001683 halVersion, deviceVersion, effectiveApiLevel,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001684 /*out*/&tmp)).isOk()) {
1685 return ret;
1686 }
1687 client = static_cast<CLIENT*>(tmp.get());
1688
1689 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1690 __FUNCTION__);
1691
Emilian Peevbd8c5032018-02-14 23:05:40 +00001692 err = client->initialize(mCameraProviderManager, mMonitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001693 if (err != OK) {
1694 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001695 // Errors could be from the HAL module open call or from AppOpsManager
1696 switch(err) {
1697 case BAD_VALUE:
1698 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1699 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1700 case -EBUSY:
1701 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1702 "Camera \"%s\" is already open", cameraId.string());
1703 case -EUSERS:
1704 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1705 "Too many cameras already open, cannot open camera \"%s\"",
1706 cameraId.string());
1707 case PERMISSION_DENIED:
1708 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1709 "No permission to open camera \"%s\"", cameraId.string());
1710 case -EACCES:
1711 return STATUS_ERROR_FMT(ERROR_DISABLED,
1712 "Camera \"%s\" disabled by policy", cameraId.string());
1713 case -ENODEV:
1714 default:
1715 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1716 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1717 strerror(-err), err);
1718 }
1719 }
1720
1721 // Update shim paremeters for legacy clients
1722 if (effectiveApiLevel == API_1) {
1723 // Assume we have always received a Client subclass for API1
1724 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1725 String8 rawParams = shimClient->getParameters();
1726 CameraParameters params(rawParams);
1727
1728 auto cameraState = getCameraState(cameraId);
1729 if (cameraState != nullptr) {
1730 cameraState->setShimParams(params);
1731 } else {
1732 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1733 __FUNCTION__, cameraId.string());
1734 }
1735 }
1736
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001737 // Set rotate-and-crop override behavior
1738 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1739 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
1740 }
1741
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001742 if (shimUpdateOnly) {
1743 // If only updating legacy shim parameters, immediately disconnect client
1744 mServiceLock.unlock();
1745 client->disconnect();
1746 mServiceLock.lock();
1747 } else {
1748 // Otherwise, add client to active clients list
1749 finishConnectLocked(client, partial);
1750 }
1751 } // lock is destroyed, allow further connect calls
1752
1753 // Important: release the mutex here so the client can call back into the service from its
1754 // destructor (can be at the end of the call)
1755 device = client;
1756 return ret;
1757}
1758
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001759status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
1760 if (offlineClient.get() == nullptr) {
1761 return BAD_VALUE;
1762 }
1763
1764 {
1765 // Acquire mServiceLock and prevent other clients from connecting
1766 std::unique_ptr<AutoConditionLock> lock =
1767 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1768
1769 if (lock == nullptr) {
1770 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
1771 , __FUNCTION__, offlineClient->getClientPid());
1772 return TIMED_OUT;
1773 }
1774
1775 auto onlineClientDesc = mActiveClientManager.get(cameraId);
1776 if (onlineClientDesc.get() == nullptr) {
1777 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
1778 cameraId.c_str());
1779 return BAD_VALUE;
1780 }
1781
1782 // Offline clients do not evict or conflict with other online devices. Resource sharing
1783 // conflicts are handled by the camera provider which will either succeed or fail before
1784 // reaching this method.
1785 const auto& onlinePriority = onlineClientDesc->getPriority();
1786 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
1787 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
1788 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
1789 onlineClientDesc->getOwnerId(), onlinePriority.getState());
1790
1791 // Allow only one offline device per camera
1792 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
1793 if (!incompatibleClients.empty()) {
1794 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
1795 return BAD_VALUE;
1796 }
1797
1798 auto err = offlineClient->initialize(mCameraProviderManager, mMonitorTags);
1799 if (err != OK) {
1800 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
1801 return err;
1802 }
1803
1804 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
1805 if (evicted.size() > 0) {
1806 for (auto& i : evicted) {
1807 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
1808 __FUNCTION__, i->getKey().string());
1809 }
1810
1811 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
1812 "properly", __FUNCTION__);
1813
1814 return BAD_VALUE;
1815 }
1816
1817 logConnectedOffline(offlineClientDesc->getKey(),
1818 static_cast<int>(offlineClientDesc->getOwnerId()),
1819 String8(offlineClient->getPackageName()));
1820
1821 sp<IBinder> remoteCallback = offlineClient->getRemote();
1822 if (remoteCallback != nullptr) {
1823 remoteCallback->linkToDeath(this);
1824 }
1825 } // lock is destroyed, allow further connect calls
1826
1827 return OK;
1828}
1829
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001830Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001831 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001832 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001833
1834 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001835 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001836 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001837 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1838 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001839 }
1840
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001841 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07001842 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001843
1844 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001845 auto state = getCameraState(id);
1846 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001847 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001848 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1849 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001850 }
1851
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001852 StatusInternal cameraStatus = state->getStatus();
1853 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001854 cameraStatus != StatusInternal::NOT_AVAILABLE) {
1855 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001856 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1857 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001858 }
1859
1860 {
1861 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001862 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001863 status_t err = getTorchStatusLocked(id, &status);
1864 if (err != OK) {
1865 if (err == NAME_NOT_FOUND) {
1866 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1867 "Camera \"%s\" does not have a flash unit", id.string());
1868 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001869 ALOGE("%s: getting current torch status failed for camera %s",
1870 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001871 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1872 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
1873 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001874 }
1875
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001876 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001877 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001878 ALOGE("%s: torch mode of camera %s is not available because "
1879 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001880 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1881 "Torch for camera \"%s\" is not available due to an existing camera user",
1882 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001883 } else {
1884 ALOGE("%s: torch mode of camera %s is not available due to "
1885 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001886 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1887 "Torch for camera \"%s\" is not available due to insufficient resources",
1888 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001889 }
1890 }
1891 }
1892
Ruben Brunk99e69712015-05-26 17:25:07 -07001893 {
1894 // Update UID map - this is used in the torch status changed callbacks, so must be done
1895 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001896 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001897 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1898 mTorchUidMap[id].first = uid;
1899 mTorchUidMap[id].second = uid;
1900 } else {
1901 // Set the pending UID
1902 mTorchUidMap[id].first = uid;
1903 }
1904 }
1905
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001906 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001907
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001908 if (err != OK) {
1909 int32_t errorCode;
1910 String8 msg;
1911 switch (err) {
1912 case -ENOSYS:
1913 msg = String8::format("Camera \"%s\" has no flashlight",
1914 id.string());
1915 errorCode = ERROR_ILLEGAL_ARGUMENT;
1916 break;
1917 default:
1918 msg = String8::format(
1919 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1920 id.string(), enabled, strerror(-err), err);
1921 errorCode = ERROR_INVALID_OPERATION;
1922 }
1923 ALOGE("%s: %s", __FUNCTION__, msg.string());
1924 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001925 }
1926
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001927 {
1928 // update the link to client's death
1929 Mutex::Autolock al(mTorchClientMapMutex);
1930 ssize_t index = mTorchClientMap.indexOfKey(id);
1931 if (enabled) {
1932 if (index == NAME_NOT_FOUND) {
1933 mTorchClientMap.add(id, clientBinder);
1934 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001935 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001936 mTorchClientMap.replaceValueAt(index, clientBinder);
1937 }
1938 clientBinder->linkToDeath(this);
1939 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001940 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001941 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001942 }
1943
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07001944 int clientPid = CameraThreadState::getCallingPid();
1945 const char *id_cstr = id.c_str();
1946 const char *torchState = enabled ? "on" : "off";
1947 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
1948 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001949 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001950}
1951
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001952Status CameraService::notifySystemEvent(int32_t eventId,
1953 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001954 const int pid = CameraThreadState::getCallingPid();
1955 const int selfPid = getpid();
1956
1957 // Permission checks
1958 if (pid != selfPid) {
1959 // Ensure we're being called by system_server, or similar process with
1960 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001961 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001962 const int uid = CameraThreadState::getCallingUid();
1963 ALOGE("Permission Denial: cannot send updates to camera service about system"
1964 " events from pid=%d, uid=%d", pid, uid);
1965 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09001966 "No permission to send updates to camera service about system events"
1967 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001968 }
1969 }
1970
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001971 ATRACE_CALL();
1972
Ruben Brunk36597b22015-03-20 22:15:57 -07001973 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001974 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001975 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07001976 // from a system server crash
1977 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08001978 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001979 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07001980 break;
1981 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001982 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07001983 default: {
1984 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1985 eventId);
1986 break;
1987 }
1988 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001989 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07001990}
1991
Emilian Peev53722fa2019-02-22 17:47:20 -08001992void CameraService::notifyMonitoredUids() {
1993 Mutex::Autolock lock(mStatusListenerLock);
1994
1995 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001996 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08001997 if (!ret.isOk()) {
1998 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
1999 ret.exceptionCode());
2000 }
2001 }
2002}
2003
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002004Status CameraService::notifyDeviceStateChange(int64_t newState) {
2005 const int pid = CameraThreadState::getCallingPid();
2006 const int selfPid = getpid();
2007
2008 // Permission checks
2009 if (pid != selfPid) {
2010 // Ensure we're being called by system_server, or similar process with
2011 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002012 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002013 const int uid = CameraThreadState::getCallingUid();
2014 ALOGE("Permission Denial: cannot send updates to camera service about device"
2015 " state changes from pid=%d, uid=%d", pid, uid);
2016 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2017 "No permission to send updates to camera service about device state"
2018 " changes from pid=%d, uid=%d", pid, uid);
2019 }
2020 }
2021
2022 ATRACE_CALL();
2023
2024 using hardware::camera::provider::V2_5::DeviceState;
2025 hardware::hidl_bitfield<DeviceState> newDeviceState{};
2026 if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
2027 newDeviceState |= DeviceState::BACK_COVERED;
2028 }
2029 if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
2030 newDeviceState |= DeviceState::FRONT_COVERED;
2031 }
2032 if (newState & ICameraService::DEVICE_STATE_FOLDED) {
2033 newDeviceState |= DeviceState::FOLDED;
2034 }
2035 // Only map vendor bits directly
2036 uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
2037 newDeviceState |= vendorBits;
2038
2039 ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
2040 Mutex::Autolock l(mServiceLock);
2041 mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
2042
2043 return Status::ok();
2044}
2045
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002046 Status CameraService::getConcurrentStreamingCameraIds(
2047 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2048 ATRACE_CALL();
2049 if (!concurrentCameraIds) {
2050 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2051 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2052 }
2053
2054 if (!mInitialized) {
2055 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2056 return STATUS_ERROR(ERROR_DISCONNECTED,
2057 "Camera subsystem is not available");
2058 }
2059 // First call into the provider and get the set of concurrent camera
2060 // combinations
2061 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
2062 mCameraProviderManager->getConcurrentStreamingCameraIds();
2063 for (auto &combination : concurrentCameraCombinations) {
2064 std::vector<std::string> validCombination;
2065 for (auto &cameraId : combination) {
2066 // if the camera state is not present, skip
2067 String8 cameraIdStr(cameraId.c_str());
2068 auto state = getCameraState(cameraIdStr);
2069 if (state == nullptr) {
2070 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2071 continue;
2072 }
2073 StatusInternal status = state->getStatus();
2074 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2075 continue;
2076 }
2077 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2078 continue;
2079 }
2080 validCombination.push_back(cameraId);
2081 }
2082 if (validCombination.size() != 0) {
2083 concurrentCameraIds->push_back(std::move(validCombination));
2084 }
2085 }
2086 return Status::ok();
2087}
2088
2089Status CameraService::isConcurrentSessionConfigurationSupported(
2090 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
2091 /*out*/bool* isSupported) {
2092 if (!isSupported) {
2093 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2094 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2095 }
2096
2097 if (!mInitialized) {
2098 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2099 return STATUS_ERROR(ERROR_DISCONNECTED,
2100 "Camera subsystem is not available");
2101 }
2102
2103 // Check for camera permissions
2104 int callingPid = CameraThreadState::getCallingPid();
2105 int callingUid = CameraThreadState::getCallingUid();
2106 if ((callingPid != getpid()) && !checkPermission(sCameraPermission, callingPid, callingUid)) {
2107 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2108 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2109 "android.permission.CAMERA needed to call"
2110 "isConcurrentSessionConfigurationSupported");
2111 }
2112
2113 status_t res =
2114 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
2115 cameraIdsAndSessionConfigurations, isSupported);
2116 if (res != OK) {
2117 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2118 "support %s (%d)", strerror(-res), res);
2119 }
2120 return Status::ok();
2121}
2122
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002123Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2124 /*out*/
2125 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002126 return addListenerHelper(listener, cameraStatuses);
2127}
2128
2129Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2130 /*out*/
2131 std::vector<hardware::CameraStatus> *cameraStatuses,
2132 bool isVendorListener) {
2133
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002134 ATRACE_CALL();
2135
Igor Murashkinbfc99152013-02-27 12:55:20 -08002136 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002137
Ruben Brunk3450ba72015-06-16 11:00:37 -07002138 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002139 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002140 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002141 }
2142
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002143 auto clientUid = CameraThreadState::getCallingUid();
2144 auto clientPid = CameraThreadState::getCallingPid();
2145
Igor Murashkinbfc99152013-02-27 12:55:20 -08002146 Mutex::Autolock lock(mServiceLock);
2147
Ruben Brunkcc776712015-02-17 20:18:47 -08002148 {
2149 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002150 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002151 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002152 ALOGW("%s: Tried to add listener %p which was already subscribed",
2153 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002154 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002155 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002156 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002157
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002158 sp<ServiceListener> serviceListener =
2159 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002160 auto ret = serviceListener->initialize();
2161 if (ret != NO_ERROR) {
2162 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2163 strerror(-ret), ret);
2164 ALOGE("%s: %s", __FUNCTION__, msg.string());
2165 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2166 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002167 // The listener still needs to be added to the list of listeners, regardless of what
2168 // permissions the listener process has / whether it is a vendor listener. Since it might be
2169 // eligible to listen to other camera ids.
2170 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002171 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002172 }
2173
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002174 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002175 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002176 Mutex::Autolock lock(mCameraStatesLock);
2177 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002178 cameraStatuses->emplace_back(i.first,
2179 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds());
Igor Murashkincba2c162013-03-20 15:56:31 -07002180 }
2181 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002182 // Remove the camera statuses that should be hidden from the client, we do
2183 // this after collecting the states in order to avoid holding
2184 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2185 // the same time.
2186 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2187 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2188 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2189 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2190 ALOGE("%s: Invalid camera id %s, skipping status update",
2191 __FUNCTION__, s.cameraId.c_str());
2192 return true;
2193 }
2194 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2195 clientUid);}), cameraStatuses->end());
2196
Igor Murashkincba2c162013-03-20 15:56:31 -07002197
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002198 /*
2199 * Immediately signal current torch status to this listener only
2200 * This may be a subset of all the devices, so don't include it in the response directly
2201 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002202 {
2203 Mutex::Autolock al(mTorchStatusMutex);
2204 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002205 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002206 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002207 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002208 }
2209
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002210 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002211}
Ruben Brunkcc776712015-02-17 20:18:47 -08002212
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002213Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002214 ATRACE_CALL();
2215
Igor Murashkinbfc99152013-02-27 12:55:20 -08002216 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2217
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002218 if (listener == 0) {
2219 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002220 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002221 }
2222
Igor Murashkinbfc99152013-02-27 12:55:20 -08002223 Mutex::Autolock lock(mServiceLock);
2224
Ruben Brunkcc776712015-02-17 20:18:47 -08002225 {
2226 Mutex::Autolock lock(mStatusListenerLock);
2227 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002228 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2229 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2230 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002231 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002232 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002233 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002234 }
2235 }
2236
2237 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2238 __FUNCTION__, listener.get());
2239
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002240 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002241}
2242
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002243Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002244
2245 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002246 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2247
2248 if (parameters == NULL) {
2249 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002250 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002251 }
2252
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002253 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002254
2255 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002256 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002257 // Error logged by caller
2258 return ret;
2259 }
2260
2261 String8 shimParamsString8 = shimParams.flatten();
2262 String16 shimParamsString16 = String16(shimParamsString8);
2263
2264 *parameters = shimParamsString16;
2265
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002266 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002267}
2268
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002269Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2270 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002271 ATRACE_CALL();
2272
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002273 const String8 id = String8(cameraId);
2274
2275 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002276
2277 switch (apiVersion) {
2278 case API_VERSION_1:
2279 case API_VERSION_2:
2280 break;
2281 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002282 String8 msg = String8::format("Unknown API version %d", apiVersion);
2283 ALOGE("%s: %s", __FUNCTION__, msg.string());
2284 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002285 }
2286
Emilian Peev28ad2ea2017-02-07 16:14:32 +00002287 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002288 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002289 case CAMERA_DEVICE_API_VERSION_1_0:
2290 case CAMERA_DEVICE_API_VERSION_3_0:
2291 case CAMERA_DEVICE_API_VERSION_3_1:
2292 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002293 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2294 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002295 *isSupported = false;
2296 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002297 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2298 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002299 *isSupported = true;
2300 }
2301 break;
2302 case CAMERA_DEVICE_API_VERSION_3_2:
2303 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07002304 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002305 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -08002306 case CAMERA_DEVICE_API_VERSION_3_6:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002307 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2308 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002309 *isSupported = true;
2310 break;
2311 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002312 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002313 ALOGE("%s: %s", __FUNCTION__, msg.string());
2314 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002315 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002316 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002317 String8 msg = String8::format("Unknown device version %x for device %s",
2318 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002319 ALOGE("%s: %s", __FUNCTION__, msg.string());
2320 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2321 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002322 }
2323
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002324 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002325}
2326
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002327Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2328 /*out*/ bool *isSupported) {
2329 ATRACE_CALL();
2330
2331 const String8 id = String8(cameraId);
2332
2333 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2334 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2335
2336 return Status::ok();
2337}
2338
Ruben Brunkcc776712015-02-17 20:18:47 -08002339void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002340 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002341 for (auto& i : mActiveClientManager.getAll()) {
2342 auto clientSp = i->getValue();
2343 if (clientSp.get() == client) {
2344 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002345 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002346 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002347 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002348}
2349
Ruben Brunkcc776712015-02-17 20:18:47 -08002350bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002351 bool ret = false;
2352 {
2353 // Acquire mServiceLock and prevent other clients from connecting
2354 std::unique_ptr<AutoConditionLock> lock =
2355 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002356
Igor Murashkin634a5152013-02-20 17:15:11 -08002357
Ruben Brunkcc776712015-02-17 20:18:47 -08002358 std::vector<sp<BasicClient>> evicted;
2359 for (auto& i : mActiveClientManager.getAll()) {
2360 auto clientSp = i->getValue();
2361 if (clientSp.get() == nullptr) {
2362 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2363 mActiveClientManager.remove(i);
2364 continue;
2365 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002366 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002367 mActiveClientManager.remove(i);
2368 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002369
Ruben Brunkcc776712015-02-17 20:18:47 -08002370 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002371 clientSp->notifyError(
2372 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002373 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002374 }
2375 }
2376
Ruben Brunkcc776712015-02-17 20:18:47 -08002377 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2378 // other clients from connecting in mServiceLockWrapper if held
2379 mServiceLock.unlock();
2380
Ruben Brunk36597b22015-03-20 22:15:57 -07002381 // Do not clear caller identity, remote caller should be client proccess
2382
Ruben Brunkcc776712015-02-17 20:18:47 -08002383 for (auto& i : evicted) {
2384 if (i.get() != nullptr) {
2385 i->disconnect();
2386 ret = true;
2387 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002388 }
2389
Ruben Brunkcc776712015-02-17 20:18:47 -08002390 // Reacquire mServiceLock
2391 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002392
Ruben Brunkcc776712015-02-17 20:18:47 -08002393 } // lock is destroyed, allow further connect calls
2394
2395 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002396}
2397
Ruben Brunkcc776712015-02-17 20:18:47 -08002398std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2399 const String8& cameraId) const {
2400 std::shared_ptr<CameraState> state;
2401 {
2402 Mutex::Autolock lock(mCameraStatesLock);
2403 auto iter = mCameraStates.find(cameraId);
2404 if (iter != mCameraStates.end()) {
2405 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002406 }
2407 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002408 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002409}
2410
Ruben Brunkcc776712015-02-17 20:18:47 -08002411sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2412 // Remove from active clients list
2413 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2414 if (clientDescriptorPtr == nullptr) {
2415 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2416 cameraId.string());
2417 return sp<BasicClient>{nullptr};
2418 }
2419
2420 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07002421}
2422
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002423void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002424 // Acquire mServiceLock and prevent other clients from connecting
2425 std::unique_ptr<AutoConditionLock> lock =
2426 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2427
Ruben Brunk6267b532015-04-30 17:44:07 -07002428 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002429 for (size_t i = 0; i < newUserIds.size(); i++) {
2430 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002431 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002432 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002433 return;
2434 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002435 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002436 }
2437
Ruben Brunka8ca9152015-04-07 14:23:40 -07002438
Ruben Brunk6267b532015-04-30 17:44:07 -07002439 if (newAllowedUsers == mAllowedUsers) {
2440 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2441 return;
2442 }
2443
2444 logUserSwitch(mAllowedUsers, newAllowedUsers);
2445
2446 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002447
2448 // Current user has switched, evict all current clients.
2449 std::vector<sp<BasicClient>> evicted;
2450 for (auto& i : mActiveClientManager.getAll()) {
2451 auto clientSp = i->getValue();
2452
2453 if (clientSp.get() == nullptr) {
2454 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2455 continue;
2456 }
2457
Ruben Brunk6267b532015-04-30 17:44:07 -07002458 // Don't evict clients that are still allowed.
2459 uid_t clientUid = clientSp->getClientUid();
2460 userid_t clientUserId = multiuser_get_user_id(clientUid);
2461 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2462 continue;
2463 }
2464
Ruben Brunk36597b22015-03-20 22:15:57 -07002465 evicted.push_back(clientSp);
2466
2467 String8 curTime = getFormattedCurrentTime();
2468
2469 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2470 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002471
Ruben Brunk36597b22015-03-20 22:15:57 -07002472 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002473 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002474 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2475 " to user switch.", i->getKey().string(),
2476 String8{clientSp->getPackageName()}.string(),
2477 i->getOwnerId(), i->getPriority().getScore(),
2478 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002479
2480 }
2481
2482 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2483 // blocking other clients from connecting in mServiceLockWrapper if held.
2484 mServiceLock.unlock();
2485
2486 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002487 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002488
2489 for (auto& i : evicted) {
2490 i->disconnect();
2491 }
2492
Jayant Chowdhary12361932018-08-27 14:46:13 -07002493 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002494
2495 // Reacquire mServiceLock
2496 mServiceLock.lock();
2497}
Ruben Brunkcc776712015-02-17 20:18:47 -08002498
Ruben Brunka8ca9152015-04-07 14:23:40 -07002499void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002500 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002501 Mutex::Autolock l(mLogLock);
2502 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002503}
2504
Ruben Brunka8ca9152015-04-07 14:23:40 -07002505void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002506 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002507 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002508 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002509 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002510}
2511
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002512void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
2513 const char* clientPackage) {
2514 // Log the clients evicted
2515 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
2516 cameraId, clientPackage, clientPid));
2517}
2518
Ruben Brunka8ca9152015-04-07 14:23:40 -07002519void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002520 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002521 // Log the clients evicted
2522 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002523 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002524}
2525
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002526void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
2527 const char* clientPackage) {
2528 // Log the clients evicted
2529 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
2530 clientPackage, clientPid));
2531}
2532
Ruben Brunka8ca9152015-04-07 14:23:40 -07002533void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002534 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002535 // Log the client rejected
2536 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002537 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002538}
2539
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002540void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
2541 // Log torch event
2542 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
2543 torchState, clientPid));
2544}
2545
Ruben Brunk6267b532015-04-30 17:44:07 -07002546void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
2547 const std::set<userid_t>& newUserIds) {
2548 String8 newUsers = toString(newUserIds);
2549 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002550 if (oldUsers.size() == 0) {
2551 oldUsers = "<None>";
2552 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07002553 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002554 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07002555 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002556}
2557
2558void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
2559 // Log the device removal
2560 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
2561}
2562
2563void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
2564 // Log the device removal
2565 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
2566}
2567
2568void CameraService::logClientDied(int clientPid, const char* reason) {
2569 // Log the device removal
2570 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07002571}
2572
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002573void CameraService::logServiceError(const char* msg, int errorCode) {
2574 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002575 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002576}
2577
Ruben Brunk36597b22015-03-20 22:15:57 -07002578status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
2579 uint32_t flags) {
2580
Mathias Agopian65ab4712010-07-14 17:59:35 -07002581 // Permission checks
2582 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002583 case SHELL_COMMAND_TRANSACTION: {
2584 int in = data.readFileDescriptor();
2585 int out = data.readFileDescriptor();
2586 int err = data.readFileDescriptor();
2587 int argc = data.readInt32();
2588 Vector<String16> args;
2589 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
2590 args.add(data.readString16());
2591 }
2592 sp<IBinder> unusedCallback;
2593 sp<IResultReceiver> resultReceiver;
2594 status_t status;
2595 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
2596 return status;
2597 }
2598 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
2599 return status;
2600 }
2601 status = shellCommand(in, out, err, args);
2602 if (resultReceiver != nullptr) {
2603 resultReceiver->send(status);
2604 }
2605 return NO_ERROR;
2606 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002607 }
2608
2609 return BnCameraService::onTransact(code, data, reply, flags);
2610}
2611
Mathias Agopian65ab4712010-07-14 17:59:35 -07002612// We share the media players for shutter and recording sound for all clients.
2613// A reference count is kept to determine when we will actually release the
2614// media players.
2615
Jaekyun Seokef498052018-03-23 13:09:44 +09002616sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
2617 sp<MediaPlayer> mp = new MediaPlayer();
2618 status_t error;
2619 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08002620 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09002621 error = mp->prepare();
2622 }
2623 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002624 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09002625 mp->disconnect();
2626 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002627 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002628 }
2629 return mp;
2630}
2631
username5755fea2018-12-27 09:48:08 +08002632void CameraService::increaseSoundRef() {
2633 Mutex::Autolock lock(mSoundLock);
2634 mSoundRef++;
2635}
2636
2637void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002638 ATRACE_CALL();
2639
username5755fea2018-12-27 09:48:08 +08002640 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
2641 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
2642 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
2643 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
2644 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2645 }
2646 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
2647 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
2648 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
2649 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002650 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08002651 }
2652 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
2653 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
2654 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
2655 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2656 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002657 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002658}
2659
username5755fea2018-12-27 09:48:08 +08002660void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002661 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002662 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002663 if (--mSoundRef) return;
2664
2665 for (int i = 0; i < NUM_SOUNDS; i++) {
2666 if (mSoundPlayer[i] != 0) {
2667 mSoundPlayer[i]->disconnect();
2668 mSoundPlayer[i].clear();
2669 }
2670 }
2671}
2672
2673void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002674 ATRACE_CALL();
2675
Mathias Agopian65ab4712010-07-14 17:59:35 -07002676 LOG1("playSound(%d)", kind);
2677 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002678 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002679 sp<MediaPlayer> player = mSoundPlayer[kind];
2680 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08002681 player->seekTo(0);
2682 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002683 }
2684}
2685
2686// ----------------------------------------------------------------------------
2687
2688CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002689 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002690 const String16& clientPackageName,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002691 const std::unique_ptr<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002692 const String8& cameraIdStr,
2693 int api1CameraId, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002694 int clientPid, uid_t clientUid,
2695 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002696 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08002697 IInterface::asBinder(cameraClient),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002698 clientPackageName, clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002699 cameraIdStr, cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002700 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002701 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002702 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08002703{
Jayant Chowdhary12361932018-08-27 14:46:13 -07002704 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002705 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002706
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002707 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002708
username5755fea2018-12-27 09:48:08 +08002709 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002710
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002711 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002712}
2713
Mathias Agopian65ab4712010-07-14 17:59:35 -07002714// tear down the client
2715CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002716 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08002717 mDestructionStarted = true;
2718
username5755fea2018-12-27 09:48:08 +08002719 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002720 // unconditionally disconnect. function is idempotent
2721 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002722}
2723
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002724sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
2725
Igor Murashkin634a5152013-02-20 17:15:11 -08002726CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002727 const sp<IBinder>& remoteCallback,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002728 const String16& clientPackageName, const std::unique_ptr<String16>& clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002729 const String8& cameraIdStr, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002730 int clientPid, uid_t clientUid,
2731 int servicePid):
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002732 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002733 mClientPackageName(clientPackageName),
2734 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002735 mServicePid(servicePid),
2736 mDisconnected(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002737 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002738 mRemoteBinder(remoteCallback)
Igor Murashkin634a5152013-02-20 17:15:11 -08002739{
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002740 if (clientFeatureId) {
2741 mClientFeatureId = std::unique_ptr<String16>(new String16(*clientFeatureId));
2742 } else {
2743 mClientFeatureId = std::unique_ptr<String16>();
2744 }
2745
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002746 if (sCameraService == nullptr) {
2747 sCameraService = cameraService;
2748 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002749 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08002750 mDestructionStarted = false;
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08002751
2752 // In some cases the calling code has no access to the package it runs under.
2753 // For example, NDK camera API.
2754 // In this case we will get the packages for the calling UID and pick the first one
2755 // for attributing the app op. This will work correctly for runtime permissions
2756 // as for legacy apps we will toggle the app op for all packages in the UID.
2757 // The caveat is that the operation may be attributed to the wrong package and
2758 // stats based on app ops may be slightly off.
2759 if (mClientPackageName.size() <= 0) {
2760 sp<IServiceManager> sm = defaultServiceManager();
2761 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2762 if (binder == 0) {
2763 ALOGE("Cannot get permission service");
2764 // Leave mClientPackageName unchanged (empty) and the further interaction
2765 // with camera will fail in BasicClient::startCameraOps
2766 return;
2767 }
2768
2769 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2770 Vector<String16> packages;
2771
2772 permCtrl->getPackagesForUid(mClientUid, packages);
2773
2774 if (packages.isEmpty()) {
2775 ALOGE("No packages for calling UID");
2776 // Leave mClientPackageName unchanged (empty) and the further interaction
2777 // with camera will fail in BasicClient::startCameraOps
2778 return;
2779 }
2780 mClientPackageName = packages[0];
2781 }
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002782 if (!hardware::IPCThreadState::self()->isServingCall()) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002783 mAppOpsManager = std::make_unique<AppOpsManager>();
2784 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002785}
2786
2787CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002788 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08002789 mDestructionStarted = true;
2790}
2791
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002792binder::Status CameraService::BasicClient::disconnect() {
2793 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002794 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002795 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07002796 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002797 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002798
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002799 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002800 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07002801 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
2802 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002803
2804 sp<IBinder> remote = getRemote();
2805 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002806 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08002807 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002808
2809 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07002810 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002811 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
2812 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
2813 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002814
Igor Murashkincba2c162013-03-20 15:56:31 -07002815 // client shouldn't be able to call into us anymore
2816 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002817
2818 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08002819}
2820
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002821status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2822 // No dumping of clients directly over Binder,
2823 // must go through CameraService::dump
2824 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002825 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002826 return OK;
2827}
2828
Ruben Brunkcc776712015-02-17 20:18:47 -08002829String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002830 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08002831}
2832
2833
2834int CameraService::BasicClient::getClientPid() const {
2835 return mClientPid;
2836}
2837
Ruben Brunk6267b532015-04-30 17:44:07 -07002838uid_t CameraService::BasicClient::getClientUid() const {
2839 return mClientUid;
2840}
2841
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002842bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2843 // Defaults to API2.
2844 return level == API_2;
2845}
2846
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002847status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002848 {
2849 Mutex::Autolock l(mAudioRestrictionLock);
2850 mAudioRestriction = mode;
2851 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002852 sCameraService->updateAudioRestriction();
2853 return OK;
2854}
2855
2856int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002857 return sCameraService->updateAudioRestriction();
2858}
2859
2860int32_t CameraService::BasicClient::getAudioRestriction() const {
2861 Mutex::Autolock l(mAudioRestrictionLock);
2862 return mAudioRestriction;
2863}
2864
2865bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
2866 switch (mode) {
2867 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
2868 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
2869 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
2870 return true;
2871 default:
2872 return false;
2873 }
2874}
2875
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002876status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002877 ATRACE_CALL();
2878
Igor Murashkine6800ce2013-03-04 17:25:57 -08002879 {
2880 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002881 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002882 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002883 if (mAppOpsManager != nullptr) {
2884 // Notify app ops that the camera is not available
2885 mOpsCallback = new OpsCallback(this);
2886 int32_t res;
2887 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
2888 mClientPackageName, mOpsCallback);
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002889 res = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
2890 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
2891 String16("start camera ") + String16(mCameraIdStr));
Igor Murashkine6800ce2013-03-04 17:25:57 -08002892
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002893 if (res == AppOpsManager::MODE_ERRORED) {
2894 ALOGI("Camera %s: Access for \"%s\" has been revoked",
2895 mCameraIdStr.string(), String8(mClientPackageName).string());
2896 return PERMISSION_DENIED;
2897 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002898
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002899 if (res == AppOpsManager::MODE_IGNORED) {
2900 ALOGI("Camera %s: Access for \"%s\" has been restricted",
2901 mCameraIdStr.string(), String8(mClientPackageName).string());
2902 // Return the same error as for device policy manager rejection
2903 return -EACCES;
2904 }
Svetoslav28e8ef72015-05-11 19:21:31 -07002905 }
2906
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002907 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002908
2909 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002910 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002911
Emilian Peev573291c2018-02-10 02:10:56 +00002912 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2913 if (canCastToApiClient(API_2)) {
2914 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2915 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002916 // Transition device state to OPEN
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002917 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
Emilian Peev573291c2018-02-10 02:10:56 +00002918 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002919
Emilian Peev53722fa2019-02-22 17:47:20 -08002920 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
2921
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002922 return OK;
2923}
2924
2925status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002926 ATRACE_CALL();
2927
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002928 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002929 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002930 // Notify app ops that the camera is available again
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002931 if (mAppOpsManager != nullptr) {
2932 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002933 mClientPackageName, mClientFeatureId);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002934 mOpsActive = false;
2935 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002936 // This function is called when a client disconnects. This should
2937 // release the camera, but actually only if it was in a proper
2938 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002939 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002940 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002941
Ruben Brunkcc776712015-02-17 20:18:47 -08002942 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002943 sCameraService->updateStatus(StatusInternal::PRESENT,
2944 mCameraIdStr, rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002945
Emilian Peev573291c2018-02-10 02:10:56 +00002946 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2947 if (canCastToApiClient(API_2)) {
2948 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2949 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002950 // Transition device state to CLOSED
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002951 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
Emilian Peev573291c2018-02-10 02:10:56 +00002952 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002953 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002954 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002955 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
2956 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002957 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002958 mOpsCallback.clear();
2959
Emilian Peev53722fa2019-02-22 17:47:20 -08002960 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
2961
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002962 return OK;
2963}
2964
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002965void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002966 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002967 if (mAppOpsManager == nullptr) {
2968 return;
2969 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002970 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002971 if (op != AppOpsManager::OP_CAMERA) {
2972 ALOGW("Unexpected app ops notification received: %d", op);
2973 return;
2974 }
2975
2976 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002977 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002978 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002979 ALOGV("checkOp returns: %d, %s ", res,
2980 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
2981 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
2982 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
2983 "UNKNOWN");
2984
2985 if (res != AppOpsManager::MODE_ALLOWED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002986 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002987 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08002988 block();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002989 }
2990}
2991
Svet Ganova453d0d2018-01-11 15:37:58 -08002992void CameraService::BasicClient::block() {
2993 ATRACE_CALL();
2994
2995 // Reset the client PID to allow server-initiated disconnect,
2996 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07002997 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08002998 CaptureResultExtras resultExtras; // a dummy result (invalid)
2999 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
3000 disconnect();
3001}
3002
Mathias Agopian65ab4712010-07-14 17:59:35 -07003003// ----------------------------------------------------------------------------
3004
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003005void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07003006 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003007 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003008 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07003009 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3010 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3011 api1ErrorCode = CAMERA_ERROR_DISABLED;
3012 }
3013 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003014 } else {
3015 ALOGE("mRemoteCallback is NULL!!");
3016 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003017}
3018
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003019// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003020binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003021 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003022 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003023}
3024
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003025bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3026 return level == API_1;
3027}
3028
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003029CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3030 mClient(client) {
3031}
3032
3033void CameraService::Client::OpsCallback::opChanged(int32_t op,
3034 const String16& packageName) {
3035 sp<BasicClient> client = mClient.promote();
3036 if (client != NULL) {
3037 client->opChanged(op, packageName);
3038 }
3039}
3040
Mathias Agopian65ab4712010-07-14 17:59:35 -07003041// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003042// UidPolicy
3043// ----------------------------------------------------------------------------
3044
3045void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003046 Mutex::Autolock _l(mUidLock);
3047
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003048 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003049 status_t res = mAm.linkToDeath(this);
3050 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003051 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08003052 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08003053 ActivityManager::PROCESS_STATE_UNKNOWN,
3054 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003055 if (res == OK) {
3056 mRegistered = true;
3057 ALOGV("UidPolicy: Registered with ActivityManager");
3058 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003059}
3060
3061void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003062 Mutex::Autolock _l(mUidLock);
3063
Steven Moreland2f348142019-07-02 15:59:07 -07003064 mAm.unregisterUidObserver(this);
3065 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003066 mRegistered = false;
3067 mActiveUids.clear();
3068 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003069}
3070
3071void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3072 onUidIdle(uid, disabled);
3073}
3074
3075void CameraService::UidPolicy::onUidActive(uid_t uid) {
3076 Mutex::Autolock _l(mUidLock);
3077 mActiveUids.insert(uid);
3078}
3079
3080void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3081 bool deleted = false;
3082 {
3083 Mutex::Autolock _l(mUidLock);
3084 if (mActiveUids.erase(uid) > 0) {
3085 deleted = true;
3086 }
3087 }
3088 if (deleted) {
3089 sp<CameraService> service = mService.promote();
3090 if (service != nullptr) {
3091 service->blockClientsForUid(uid);
3092 }
3093 }
3094}
3095
Emilian Peev53722fa2019-02-22 17:47:20 -08003096void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003097 int64_t procStateSeq __unused, int32_t capability __unused) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003098 bool procStateChange = false;
3099 {
3100 Mutex::Autolock _l(mUidLock);
3101 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
3102 (mMonitoredUids[uid].first != procState)) {
3103 mMonitoredUids[uid].first = procState;
3104 procStateChange = true;
3105 }
3106 }
3107
3108 if (procStateChange) {
3109 sp<CameraService> service = mService.promote();
3110 if (service != nullptr) {
3111 service->notifyMonitoredUids();
3112 }
3113 }
3114}
3115
3116void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3117 Mutex::Autolock _l(mUidLock);
3118 auto it = mMonitoredUids.find(uid);
3119 if (it != mMonitoredUids.end()) {
3120 it->second.second++;
3121 } else {
3122 mMonitoredUids.emplace(
3123 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
3124 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
3125 }
3126}
3127
3128void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3129 Mutex::Autolock _l(mUidLock);
3130 auto it = mMonitoredUids.find(uid);
3131 if (it != mMonitoredUids.end()) {
3132 it->second.second--;
3133 if (it->second.second == 0) {
3134 mMonitoredUids.erase(it);
3135 }
3136 } else {
3137 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3138 }
3139}
3140
Svet Ganov7b4ab782018-03-25 12:48:10 -07003141bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003142 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003143 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003144}
3145
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003146static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3147static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003148
Svet Ganov7b4ab782018-03-25 12:48:10 -07003149bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003150 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003151 // If activity manager is unreachable, assume everything is active
3152 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003153 return true;
3154 }
3155 auto it = mOverrideUids.find(uid);
3156 if (it != mOverrideUids.end()) {
3157 return it->second;
3158 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003159 bool active = mActiveUids.find(uid) != mActiveUids.end();
3160 if (!active) {
3161 // We want active UIDs to always access camera with their first attempt since
3162 // there is no guarantee the app is robustly written and would retry getting
3163 // the camera on failure. The inverse case is not a problem as we would take
3164 // camera away soon once we get the callback that the uid is no longer active.
3165 ActivityManager am;
3166 // Okay to access with a lock held as UID changes are dispatched without
3167 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003168 int64_t startTimeMillis = 0;
3169 do {
3170 // TODO: Fix this b/109950150!
3171 // Okay this is a hack. There is a race between the UID turning active and
3172 // activity being resumed. The proper fix is very risky, so we temporary add
3173 // some polling which should happen pretty rarely anyway as the race is hard
3174 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003175 active = mActiveUids.find(uid) != mActiveUids.end();
3176 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003177 if (active) {
3178 break;
3179 }
3180 if (startTimeMillis <= 0) {
3181 startTimeMillis = uptimeMillis();
3182 }
3183 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003184 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003185 if (remainingTimeMillis <= 0) {
3186 break;
3187 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003188 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3189
3190 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003191 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003192 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003193 } while (true);
3194
Svet Ganov7b4ab782018-03-25 12:48:10 -07003195 if (active) {
3196 // Now that we found out the UID is actually active, cache that
3197 mActiveUids.insert(uid);
3198 }
3199 }
3200 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08003201}
3202
Varun Shahb42f1eb2019-04-16 14:45:13 -07003203int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3204 Mutex::Autolock _l(mUidLock);
3205 return getProcStateLocked(uid);
3206}
3207
3208int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3209 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3210 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3211 procState = mMonitoredUids[uid].first;
3212 }
3213 return procState;
3214}
3215
Svet Ganov7b4ab782018-03-25 12:48:10 -07003216void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3217 String16 callingPackage, bool active) {
3218 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003219}
3220
Svet Ganov7b4ab782018-03-25 12:48:10 -07003221void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3222 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003223}
3224
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003225void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3226 Mutex::Autolock _l(mUidLock);
3227 ALOGV("UidPolicy: ActivityManager has died");
3228 mRegistered = false;
3229 mActiveUids.clear();
3230}
3231
Svet Ganov7b4ab782018-03-25 12:48:10 -07003232void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3233 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003234 bool wasActive = false;
3235 bool isActive = false;
3236 {
3237 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003238 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003239 mOverrideUids.erase(uid);
3240 if (insert) {
3241 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3242 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003243 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003244 }
3245 if (wasActive != isActive && !isActive) {
3246 sp<CameraService> service = mService.promote();
3247 if (service != nullptr) {
3248 service->blockClientsForUid(uid);
3249 }
3250 }
3251}
3252
3253// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08003254// SensorPrivacyPolicy
3255// ----------------------------------------------------------------------------
3256void CameraService::SensorPrivacyPolicy::registerSelf() {
3257 Mutex::Autolock _l(mSensorPrivacyLock);
3258 if (mRegistered) {
3259 return;
3260 }
3261 SensorPrivacyManager spm;
3262 spm.addSensorPrivacyListener(this);
3263 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
3264 status_t res = spm.linkToDeath(this);
3265 if (res == OK) {
3266 mRegistered = true;
3267 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3268 }
3269}
3270
3271void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3272 Mutex::Autolock _l(mSensorPrivacyLock);
3273 SensorPrivacyManager spm;
3274 spm.removeSensorPrivacyListener(this);
3275 spm.unlinkToDeath(this);
3276 mRegistered = false;
3277 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3278}
3279
3280bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3281 Mutex::Autolock _l(mSensorPrivacyLock);
3282 return mSensorPrivacyEnabled;
3283}
3284
3285binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3286 {
3287 Mutex::Autolock _l(mSensorPrivacyLock);
3288 mSensorPrivacyEnabled = enabled;
3289 }
3290 // if sensor privacy is enabled then block all clients from accessing the camera
3291 if (enabled) {
3292 sp<CameraService> service = mService.promote();
3293 if (service != nullptr) {
3294 service->blockAllClients();
3295 }
3296 }
3297 return binder::Status::ok();
3298}
3299
3300void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3301 Mutex::Autolock _l(mSensorPrivacyLock);
3302 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3303 mRegistered = false;
3304}
3305
3306// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003307// CameraState
3308// ----------------------------------------------------------------------------
3309
3310CameraService::CameraState::CameraState(const String8& id, int cost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003311 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind) : mId(id),
3312 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
3313 mSystemCameraKind(systemCameraKind) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003314
3315CameraService::CameraState::~CameraState() {}
3316
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003317CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003318 Mutex::Autolock lock(mStatusLock);
3319 return mStatus;
3320}
3321
Shuzhen Wang43858162020-01-10 13:42:15 -08003322std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
3323 Mutex::Autolock lock(mStatusLock);
3324 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
3325 return res;
3326}
3327
Ruben Brunkcc776712015-02-17 20:18:47 -08003328CameraParameters CameraService::CameraState::getShimParams() const {
3329 return mShimParams;
3330}
3331
3332void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3333 mShimParams = params;
3334}
3335
3336int CameraService::CameraState::getCost() const {
3337 return mCost;
3338}
3339
3340std::set<String8> CameraService::CameraState::getConflicting() const {
3341 return mConflicting;
3342}
3343
3344String8 CameraService::CameraState::getId() const {
3345 return mId;
3346}
3347
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003348SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3349 return mSystemCameraKind;
3350}
3351
Shuzhen Wang43858162020-01-10 13:42:15 -08003352bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
3353 Mutex::Autolock lock(mStatusLock);
3354 auto result = mUnavailablePhysicalIds.insert(physicalId);
3355 return result.second;
3356}
3357
3358bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
3359 Mutex::Autolock lock(mStatusLock);
3360 auto count = mUnavailablePhysicalIds.erase(physicalId);
3361 return count > 0;
3362}
3363
Ruben Brunkcc776712015-02-17 20:18:47 -08003364// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07003365// ClientEventListener
3366// ----------------------------------------------------------------------------
3367
3368void CameraService::ClientEventListener::onClientAdded(
3369 const resource_policy::ClientDescriptor<String8,
3370 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003371 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003372 if (basicClient.get() != nullptr) {
3373 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3374 notifier.noteStartCamera(descriptor.getKey(),
3375 static_cast<int>(basicClient->getClientUid()));
3376 }
3377}
3378
3379void CameraService::ClientEventListener::onClientRemoved(
3380 const resource_policy::ClientDescriptor<String8,
3381 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003382 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003383 if (basicClient.get() != nullptr) {
3384 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3385 notifier.noteStopCamera(descriptor.getKey(),
3386 static_cast<int>(basicClient->getClientUid()));
3387 }
3388}
3389
3390
3391// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003392// CameraClientManager
3393// ----------------------------------------------------------------------------
3394
Ruben Brunk99e69712015-05-26 17:25:07 -07003395CameraService::CameraClientManager::CameraClientManager() {
3396 setListener(std::make_shared<ClientEventListener>());
3397}
3398
Ruben Brunkcc776712015-02-17 20:18:47 -08003399CameraService::CameraClientManager::~CameraClientManager() {}
3400
3401sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
3402 const String8& id) const {
3403 auto descriptor = get(id);
3404 if (descriptor == nullptr) {
3405 return sp<BasicClient>{nullptr};
3406 }
3407 return descriptor->getValue();
3408}
3409
3410String8 CameraService::CameraClientManager::toString() const {
3411 auto all = getAll();
3412 String8 ret("[");
3413 bool hasAny = false;
3414 for (auto& i : all) {
3415 hasAny = true;
3416 String8 key = i->getKey();
3417 int32_t cost = i->getCost();
3418 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00003419 int32_t score = i->getPriority().getScore();
3420 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08003421 auto conflicting = i->getConflicting();
3422 auto clientSp = i->getValue();
3423 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07003424 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08003425 if (clientSp.get() != nullptr) {
3426 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07003427 uid_t clientUid = clientSp->getClientUid();
3428 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003429 }
Emilian Peev8131a262017-02-01 12:33:43 +00003430 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
3431 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08003432
Ruben Brunk6267b532015-04-30 17:44:07 -07003433 if (clientSp.get() != nullptr) {
3434 ret.appendFormat("User Id: %d, ", clientUserId);
3435 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003436 if (packageName.size() != 0) {
3437 ret.appendFormat("Client Package Name: %s", packageName.string());
3438 }
3439
3440 ret.append(", Conflicting Client Devices: {");
3441 for (auto& j : conflicting) {
3442 ret.appendFormat("%s, ", j.string());
3443 }
3444 ret.append("})");
3445 }
3446 if (hasAny) ret.append("\n");
3447 ret.append("]\n");
3448 return ret;
3449}
3450
3451CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3452 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00003453 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
3454 int32_t state) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003455
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003456 bool isVendorClient = hardware::IPCThreadState::self()->isServingCall();
3457 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
3458 int32_t state_adj = isVendorClient ? kVendorClientState: state;
3459
Ruben Brunkcc776712015-02-17 20:18:47 -08003460 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003461 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08003462}
3463
3464CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3465 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
3466 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00003467 partial->getConflicting(), partial->getPriority().getScore(),
3468 partial->getOwnerId(), partial->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08003469}
3470
3471// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07003472
3473static const int kDumpLockRetries = 50;
3474static const int kDumpLockSleep = 60000;
3475
3476static bool tryLock(Mutex& mutex)
3477{
3478 bool locked = false;
3479 for (int i = 0; i < kDumpLockRetries; ++i) {
3480 if (mutex.tryLock() == NO_ERROR) {
3481 locked = true;
3482 break;
3483 }
3484 usleep(kDumpLockSleep);
3485 }
3486 return locked;
3487}
3488
3489status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003490 ATRACE_CALL();
3491
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003492 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003493 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003494 CameraThreadState::getCallingPid(),
3495 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003496 return NO_ERROR;
3497 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003498 bool locked = tryLock(mServiceLock);
3499 // failed to lock - CameraService is probably deadlocked
3500 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003501 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003502 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003503
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003504 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003505 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07003506
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003507 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003508 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08003509
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003510 if (locked) mServiceLock.unlock();
3511 return NO_ERROR;
3512 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003513 dprintf(fd, "\n== Service global info: ==\n\n");
3514 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003515 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07003516 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
3517 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003518 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
3519 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
3520 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003521 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003522 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
3523 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003524
3525 dumpEventLog(fd);
3526
3527 bool stateLocked = tryLock(mCameraStatesLock);
3528 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003529 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003530 }
3531
Emilian Peevbd8c5032018-02-14 23:05:40 +00003532 int argSize = args.size();
3533 for (int i = 0; i < argSize; i++) {
3534 if (args[i] == TagMonitor::kMonitorOption) {
3535 if (i + 1 < argSize) {
3536 mMonitorTags = String8(args[i + 1]);
3537 }
3538 break;
3539 }
3540 }
3541
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003542 for (auto& state : mCameraStates) {
3543 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003544
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003545 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003546
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003547 CameraParameters p = state.second->getShimParams();
3548 if (!p.isEmpty()) {
3549 dprintf(fd, " Camera1 API shim is using parameters:\n ");
3550 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003551 }
3552
3553 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08003554 if (clientDescriptor != nullptr) {
3555 dprintf(fd, " Device %s is open. Client instance dump:\n",
3556 cameraId.string());
3557 dprintf(fd, " Client priority score: %d state: %d\n",
3558 clientDescriptor->getPriority().getScore(),
3559 clientDescriptor->getPriority().getState());
3560 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
3561
3562 auto client = clientDescriptor->getValue();
3563 dprintf(fd, " Client package: %s\n",
3564 String8(client->getPackageName()).string());
3565
3566 client->dumpClient(fd, args);
3567 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003568 dprintf(fd, " Device %s is closed, no client instance\n",
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003569 cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003570 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003571
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003572 }
3573
3574 if (stateLocked) mCameraStatesLock.unlock();
3575
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003576 if (locked) mServiceLock.unlock();
3577
Emilian Peevf53f66e2017-04-11 14:29:43 +01003578 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003579
3580 dprintf(fd, "\n== Vendor tags: ==\n\n");
3581
3582 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
3583 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00003584 sp<VendorTagDescriptorCache> cache =
3585 VendorTagDescriptorCache::getGlobalVendorTagCache();
3586 if (cache == NULL) {
3587 dprintf(fd, "No vendor tags.\n");
3588 } else {
3589 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
3590 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003591 } else {
3592 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
3593 }
3594
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003595 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003596 dprintf(fd, "\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003597 camera3::CameraTraces::dump(fd, args);
3598
3599 // Process dump arguments, if any
3600 int n = args.size();
3601 String16 verboseOption("-v");
3602 String16 unreachableOption("--unreachable");
3603 for (int i = 0; i < n; i++) {
3604 if (args[i] == verboseOption) {
3605 // change logging level
3606 if (i + 1 >= n) continue;
3607 String8 levelStr(args[i+1]);
3608 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003609 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003610 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003611 } else if (args[i] == unreachableOption) {
3612 // Dump memory analysis
3613 // TODO - should limit be an argument parameter?
3614 UnreachableMemoryInfo info;
3615 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
3616 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003617 dprintf(fd, "\n== Unable to dump unreachable memory. "
3618 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003619 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003620 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003621 std::string s = info.ToString(/*log_contents*/ true);
3622 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003623 }
3624 }
3625 }
3626 return NO_ERROR;
3627}
3628
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003629void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003630 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003631
3632 Mutex::Autolock l(mLogLock);
3633 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003634 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003635 }
3636
3637 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003638 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003639 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003640 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003641 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003642 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003643}
3644
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003645void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003646 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003647 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
3648 if (mTorchClientMap[i] == who) {
3649 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003650 String8 cameraId = mTorchClientMap.keyAt(i);
3651 status_t res = mFlashlight->setTorchMode(cameraId, false);
3652 if (res) {
3653 ALOGE("%s: torch client died but couldn't turn off torch: "
3654 "%s (%d)", __FUNCTION__, strerror(-res), res);
3655 return;
3656 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003657 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003658 break;
3659 }
3660 }
3661}
3662
Ruben Brunkcc776712015-02-17 20:18:47 -08003663/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003664
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003665 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07003666 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
3667 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003668 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003669 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003670 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003671
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003672 // check torch client
3673 handleTorchClientBinderDied(who);
3674
3675 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08003676 if(!evictClientIdByRemote(who)) {
3677 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003678 return;
3679 }
3680
Ruben Brunkcc776712015-02-17 20:18:47 -08003681 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
3682 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003683}
3684
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003685void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003686 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08003687}
3688
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003689void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
3690 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003691 // Do not lock mServiceLock here or can get into a deadlock from
3692 // connect() -> disconnect -> updateStatus
3693
3694 auto state = getCameraState(cameraId);
3695
3696 if (state == nullptr) {
3697 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
3698 cameraId.string());
3699 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07003700 }
3701
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003702 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
3703 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3704 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3705 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
3706 return;
3707 }
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003708 bool supportsHAL3 = false;
3709 // supportsCameraApi also holds mInterfaceMutex, we can't call it in the
3710 // HIDL onStatusChanged wrapper call (we'll hold mStatusListenerLock and
3711 // mInterfaceMutex together, which can lead to deadlocks)
3712 binder::Status sRet =
3713 supportsCameraApi(String16(cameraId), hardware::ICameraService::API_VERSION_2,
3714 &supportsHAL3);
3715 if (!sRet.isOk()) {
3716 ALOGW("%s: Failed to determine if device supports HAL3 %s, supportsCameraApi call failed",
3717 __FUNCTION__, cameraId.string());
3718 return;
3719 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003720 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08003721 // of the listeners with both the mStatusLock and mStatusListenerLock held
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003722 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind, &supportsHAL3]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003723 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003724
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003725 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003726 // Update torch status if it has a flash unit.
3727 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003728 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003729 if (getTorchStatusLocked(cameraId, &torchStatus) !=
3730 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003731 TorchModeStatus newTorchStatus =
3732 status == StatusInternal::PRESENT ?
3733 TorchModeStatus::AVAILABLE_OFF :
3734 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003735 if (torchStatus != newTorchStatus) {
3736 onTorchStatusChangedLocked(cameraId, newTorchStatus);
3737 }
3738 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003739 }
3740
3741 Mutex::Autolock lock(mStatusListenerLock);
3742
Shuzhen Wang43858162020-01-10 13:42:15 -08003743 notifyPhysicalCameraStatusLocked(mapToInterface(status), cameraId);
3744
Ruben Brunkcc776712015-02-17 20:18:47 -08003745 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003746 bool isVendorListener = listener->isVendorListener();
3747 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
3748 listener->getListenerPid(), listener->getListenerUid()) ||
3749 (isVendorListener && !supportsHAL3)) {
3750 ALOGV("Skipping discovery callback for system-only camera/HAL1 device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003751 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003752 continue;
3753 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003754 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08003755 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08003756 }
3757 });
Igor Murashkincba2c162013-03-20 15:56:31 -07003758}
3759
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003760template<class Func>
3761void CameraService::CameraState::updateStatus(StatusInternal status,
3762 const String8& cameraId,
3763 std::initializer_list<StatusInternal> rejectSourceStates,
3764 Func onStatusUpdatedLocked) {
3765 Mutex::Autolock lock(mStatusLock);
3766 StatusInternal oldStatus = mStatus;
3767 mStatus = status;
3768
3769 if (oldStatus == status) {
3770 return;
3771 }
3772
3773 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
3774 cameraId.string(), oldStatus, status);
3775
3776 if (oldStatus == StatusInternal::NOT_PRESENT &&
3777 (status != StatusInternal::PRESENT &&
3778 status != StatusInternal::ENUMERATING)) {
3779
3780 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
3781 __FUNCTION__);
3782 mStatus = oldStatus;
3783 return;
3784 }
3785
3786 /**
3787 * Sometimes we want to conditionally do a transition.
3788 * For example if a client disconnects, we want to go to PRESENT
3789 * only if we weren't already in NOT_PRESENT or ENUMERATING.
3790 */
3791 for (auto& rejectStatus : rejectSourceStates) {
3792 if (oldStatus == rejectStatus) {
3793 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
3794 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
3795 mStatus = oldStatus;
3796 return;
3797 }
3798 }
3799
3800 onStatusUpdatedLocked(cameraId, status);
3801}
3802
Eino-Ville Talvalae8c96c72017-06-27 12:24:07 -07003803void CameraService::updateProxyDeviceState(int newState,
Emilian Peev573291c2018-02-10 02:10:56 +00003804 const String8& cameraId, int facing, const String16& clientName, int apiLevel) {
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003805 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
3806 if (proxyBinder == nullptr) return;
3807 String16 id(cameraId);
Emilian Peev573291c2018-02-10 02:10:56 +00003808 proxyBinder->notifyCameraState(id, newState, facing, clientName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003809}
3810
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003811status_t CameraService::getTorchStatusLocked(
3812 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003813 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003814 if (!status) {
3815 return BAD_VALUE;
3816 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003817 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3818 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003819 // invalid camera ID or the camera doesn't have a flash unit
3820 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003821 }
3822
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003823 *status = mTorchStatusMap.valueAt(index);
3824 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003825}
3826
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003827status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003828 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003829 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3830 if (index == NAME_NOT_FOUND) {
3831 return BAD_VALUE;
3832 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003833 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003834
3835 return OK;
3836}
3837
Shuzhen Wang43858162020-01-10 13:42:15 -08003838void CameraService::notifyPhysicalCameraStatusLocked(int32_t status, const String8& cameraId) {
3839 Mutex::Autolock lock(mCameraStatesLock);
3840 for (const auto& state : mCameraStates) {
3841 std::vector<std::string> physicalCameraIds;
3842 if (!mCameraProviderManager->isLogicalCamera(state.first.c_str(), &physicalCameraIds)) {
3843 // This is not a logical multi-camera.
3844 continue;
3845 }
3846 if (std::find(physicalCameraIds.begin(), physicalCameraIds.end(), cameraId.c_str())
3847 == physicalCameraIds.end()) {
3848 // cameraId is not a physical camera of this logical multi-camera.
3849 continue;
3850 }
3851
3852 String16 id16(state.first), physicalId16(cameraId);
3853 for (auto& listener : mListenerList) {
3854 listener->getListener()->onPhysicalCameraStatusChanged(status,
3855 id16, physicalId16);
3856 }
3857 }
3858}
3859
Svet Ganova453d0d2018-01-11 15:37:58 -08003860void CameraService::blockClientsForUid(uid_t uid) {
3861 const auto clients = mActiveClientManager.getAll();
3862 for (auto& current : clients) {
3863 if (current != nullptr) {
3864 const auto basicClient = current->getValue();
3865 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
3866 basicClient->block();
3867 }
3868 }
3869 }
3870}
3871
Michael Grooverd1d435a2018-12-18 17:39:42 -08003872void CameraService::blockAllClients() {
3873 const auto clients = mActiveClientManager.getAll();
3874 for (auto& current : clients) {
3875 if (current != nullptr) {
3876 const auto basicClient = current->getValue();
3877 if (basicClient.get() != nullptr) {
3878 basicClient->block();
3879 }
3880 }
3881 }
3882}
3883
Svet Ganova453d0d2018-01-11 15:37:58 -08003884// NOTE: This is a remote API - make sure all args are validated
3885status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
3886 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
3887 return PERMISSION_DENIED;
3888 }
3889 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
3890 return BAD_VALUE;
3891 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003892 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003893 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003894 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003895 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003896 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003897 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003898 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
3899 return handleSetRotateAndCrop(args);
3900 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
3901 return handleGetRotateAndCrop(out);
Svet Ganova453d0d2018-01-11 15:37:58 -08003902 } else if (args.size() == 1 && args[0] == String16("help")) {
3903 printHelp(out);
3904 return NO_ERROR;
3905 }
3906 printHelp(err);
3907 return BAD_VALUE;
3908}
3909
3910status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003911 String16 packageName = args[1];
3912
Svet Ganova453d0d2018-01-11 15:37:58 -08003913 bool active = false;
3914 if (args[2] == String16("active")) {
3915 active = true;
3916 } else if ((args[2] != String16("idle"))) {
3917 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
3918 return BAD_VALUE;
3919 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003920
3921 int userId = 0;
3922 if (args.size() >= 5 && args[3] == String16("--user")) {
3923 userId = atoi(String8(args[4]));
3924 }
3925
3926 uid_t uid;
3927 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
3928 return BAD_VALUE;
3929 }
3930
3931 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08003932 return NO_ERROR;
3933}
3934
3935status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003936 String16 packageName = args[1];
3937
3938 int userId = 0;
3939 if (args.size() >= 4 && args[2] == String16("--user")) {
3940 userId = atoi(String8(args[3]));
3941 }
3942
3943 uid_t uid;
3944 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003945 return BAD_VALUE;
3946 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003947
3948 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08003949 return NO_ERROR;
3950}
3951
3952status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003953 String16 packageName = args[1];
3954
3955 int userId = 0;
3956 if (args.size() >= 4 && args[2] == String16("--user")) {
3957 userId = atoi(String8(args[3]));
3958 }
3959
3960 uid_t uid;
3961 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003962 return BAD_VALUE;
3963 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003964
3965 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003966 return dprintf(out, "active\n");
3967 } else {
3968 return dprintf(out, "idle\n");
3969 }
3970}
3971
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003972status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
3973 int rotateValue = atoi(String8(args[1]));
3974 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
3975 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
3976 Mutex::Autolock lock(mServiceLock);
3977
3978 mOverrideRotateAndCropMode = rotateValue;
3979
3980 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
3981
3982 const auto clients = mActiveClientManager.getAll();
3983 for (auto& current : clients) {
3984 if (current != nullptr) {
3985 const auto basicClient = current->getValue();
3986 if (basicClient.get() != nullptr) {
3987 basicClient->setRotateAndCropOverride(rotateValue);
3988 }
3989 }
3990 }
3991
3992 return OK;
3993}
3994
3995status_t CameraService::handleGetRotateAndCrop(int out) {
3996 Mutex::Autolock lock(mServiceLock);
3997
3998 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
3999}
4000
Svet Ganova453d0d2018-01-11 15:37:58 -08004001status_t CameraService::printHelp(int out) {
4002 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07004003 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
4004 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
4005 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004006 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
4007 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
4008 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08004009 " help print this message\n");
4010}
4011
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004012int32_t CameraService::updateAudioRestriction() {
4013 Mutex::Autolock lock(mServiceLock);
4014 return updateAudioRestrictionLocked();
4015}
4016
4017int32_t CameraService::updateAudioRestrictionLocked() {
4018 int32_t mode = 0;
4019 // iterate through all active client
4020 for (const auto& i : mActiveClientManager.getAll()) {
4021 const auto clientSp = i->getValue();
4022 mode |= clientSp->getAudioRestriction();
4023 }
4024
4025 bool modeChanged = (mAudioRestriction != mode);
4026 mAudioRestriction = mode;
4027 if (modeChanged) {
4028 mAppOps.setCameraAudioRestriction(mode);
4029 }
4030 return mode;
4031}
4032
Mathias Agopian65ab4712010-07-14 17:59:35 -07004033}; // namespace android