blob: a5038388501782cd55c067921415c7358319e2a7 [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>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080065#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080066#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070067#include <system/camera_metadata.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080068
Ruben Brunkb2119af2014-05-09 19:57:56 -070069#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070070
71#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070072#include "api1/CameraClient.h"
73#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070074#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070075#include "utils/CameraTraces.h"
Emilian Peevbd8c5032018-02-14 23:05:40 +000076#include "utils/TagMonitor.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070077#include "utils/CameraThreadState.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070078
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080079namespace {
80 const char* kPermissionServiceName = "permission";
81}; // namespace anonymous
82
Mathias Agopian65ab4712010-07-14 17:59:35 -070083namespace android {
84
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070085using base::StringPrintf;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080086using binder::Status;
Jayant Chowdharybe543d42018-08-15 13:16:14 -070087using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -080088using hardware::ICamera;
89using hardware::ICameraClient;
Eino-Ville Talvalae8c96c72017-06-27 12:24:07 -070090using hardware::ICameraServiceProxy;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -080091using hardware::ICameraServiceListener;
92using hardware::camera::common::V1_0::CameraDeviceStatus;
93using hardware::camera::common::V1_0::TorchModeStatus;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080094
Mathias Agopian65ab4712010-07-14 17:59:35 -070095// ----------------------------------------------------------------------------
96// Logging support -- this is for debugging only
97// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -070098volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -070099
Steve Blockb8a80522011-12-20 16:23:08 +0000100#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
101#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700102
103static void setLogLevel(int level) {
104 android_atomic_write(level, &gLogLevel);
105}
106
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800107// Convenience methods for constructing binder::Status objects for error returns
108
109#define STATUS_ERROR(errorCode, errorString) \
110 binder::Status::fromServiceSpecificError(errorCode, \
111 String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
112
113#define STATUS_ERROR_FMT(errorCode, errorString, ...) \
114 binder::Status::fromServiceSpecificError(errorCode, \
115 String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, \
116 __VA_ARGS__))
117
Mathias Agopian65ab4712010-07-14 17:59:35 -0700118// ----------------------------------------------------------------------------
119
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700120static const String16 sDumpPermission("android.permission.DUMP");
Svet Ganova453d0d2018-01-11 15:37:58 -0800121static const String16 sManageCameraPermission("android.permission.MANAGE_CAMERA");
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700122static const String16 sCameraPermission("android.permission.CAMERA");
123static const String16 sSystemCameraPermission("android.permission.SYSTEM_CAMERA");
124static const String16
125 sCameraSendSystemEventsPermission("android.permission.CAMERA_SEND_SYSTEM_EVENTS");
Svet Ganova453d0d2018-01-11 15:37:58 -0800126
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700127// Matches with PERCEPTIBLE_APP_ADJ in ProcessList.java
128static constexpr int32_t kVendorClientScore = 200;
129// Matches with PROCESS_STATE_PERSISTENT_UI in ActivityManager.java
130static constexpr int32_t kVendorClientState = 1;
131
Eino-Ville Talvala7d5569f2019-04-08 13:57:54 -0700132Mutex CameraService::sProxyMutex;
133sp<hardware::ICameraServiceProxy> CameraService::sCameraServiceProxy;
134
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800135CameraService::CameraService() :
136 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800137 mNumberOfCameras(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700138 mSoundRef(0), mInitialized(false),
139 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000140 ALOGI("CameraService started (pid=%d)", getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800141 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700142}
143
Iliyan Malchev8951a972011-04-14 16:55:59 -0700144void CameraService::onFirstRef()
145{
Ruben Brunkcc776712015-02-17 20:18:47 -0800146 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800147
Iliyan Malchev8951a972011-04-14 16:55:59 -0700148 BnCameraService::onFirstRef();
149
Ruben Brunk99e69712015-05-26 17:25:07 -0700150 // Update battery life tracking if service is restarting
151 BatteryNotifier& notifier(BatteryNotifier::getInstance());
152 notifier.noteResetCamera();
153 notifier.noteResetFlashlight();
154
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800155 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800156
Emilian Peevf53f66e2017-04-11 14:29:43 +0100157 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800158 if (res == OK) {
159 mInitialized = true;
160 }
161
162 CameraService::pingCameraServiceProxy();
Svet Ganova453d0d2018-01-11 15:37:58 -0800163
164 mUidPolicy = new UidPolicy(this);
165 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800166 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
167 mSensorPrivacyPolicy->registerSelf();
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700168 mAppOps.setCameraAudioRestriction(mAudioRestriction);
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700169 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
170 if (hcs->registerAsService() != android::OK) {
171 ALOGE("%s: Failed to register default android.frameworks.cameraservice.service@1.0",
172 __FUNCTION__);
173 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800174}
175
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800176status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800177 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100178
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800179 std::vector<std::string> deviceIds;
180 {
181 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800182
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800183 if (nullptr == mCameraProviderManager.get()) {
184 mCameraProviderManager = new CameraProviderManager();
185 res = mCameraProviderManager->initialize(this);
186 if (res != OK) {
187 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
188 __FUNCTION__, strerror(-res), res);
189 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100190 }
191 }
192
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800193
194 // Setup vendor tags before we call get_camera_info the first time
195 // because HAL might need to setup static vendor keys in get_camera_info
196 // TODO: maybe put this into CameraProviderManager::initialize()?
197 mCameraProviderManager->setUpVendorTags();
198
199 if (nullptr == mFlashlight.get()) {
200 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700201 }
202
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800203 res = mFlashlight->findFlashUnits();
204 if (res != OK) {
205 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
206 }
207
208 deviceIds = mCameraProviderManager->getCameraDeviceIds();
209 }
210
211
212 for (auto& cameraId : deviceIds) {
213 String8 id8 = String8(cameraId.c_str());
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800214 if (getCameraState(id8) == nullptr) {
215 onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
216 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800217 }
218
219 return OK;
220}
221
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700222sp<ICameraServiceProxy> CameraService::getCameraServiceProxy() {
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800223#ifndef __BRILLO__
Eino-Ville Talvala7d5569f2019-04-08 13:57:54 -0700224 Mutex::Autolock al(sProxyMutex);
225 if (sCameraServiceProxy == nullptr) {
226 sp<IServiceManager> sm = defaultServiceManager();
227 // Use checkService because cameraserver normally starts before the
228 // system server and the proxy service. So the long timeout that getService
229 // has before giving up is inappropriate.
230 sp<IBinder> binder = sm->checkService(String16("media.camera.proxy"));
231 if (binder != nullptr) {
232 sCameraServiceProxy = interface_cast<ICameraServiceProxy>(binder);
233 }
Ruben Brunk2823ce02015-05-19 17:25:13 -0700234 }
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800235#endif
Eino-Ville Talvala7d5569f2019-04-08 13:57:54 -0700236 return sCameraServiceProxy;
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700237}
238
239void CameraService::pingCameraServiceProxy() {
240 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
241 if (proxyBinder == nullptr) return;
Ruben Brunk2823ce02015-05-19 17:25:13 -0700242 proxyBinder->pingForUserUpdate();
Iliyan Malchev8951a972011-04-14 16:55:59 -0700243}
244
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800245void CameraService::broadcastTorchModeStatus(const String8& cameraId, TorchModeStatus status) {
246 Mutex::Autolock lock(mStatusListenerLock);
247
248 for (auto& i : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700249 i->getListener()->onTorchStatusChanged(mapToInterface(status), String16{cameraId});
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800250 }
251}
252
Mathias Agopian65ab4712010-07-14 17:59:35 -0700253CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800254 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800255 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800256 mSensorPrivacyPolicy->unregisterSelf();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700257}
258
Emilian Peevaee727d2017-05-04 16:35:48 +0100259void CameraService::onNewProviderRegistered() {
260 enumerateProviders();
261}
262
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800263void CameraService::updateCameraNumAndIds() {
264 Mutex::Autolock l(mServiceLock);
265 mNumberOfCameras = mCameraProviderManager->getCameraCount();
266 mNormalDeviceIds =
267 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
268}
269
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100270void CameraService::addStates(const String8 id) {
271 std::string cameraId(id.c_str());
272 hardware::camera::common::V1_0::CameraResourceCost cost;
273 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
274 if (res != OK) {
275 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
276 return;
277 }
278 std::set<String8> conflicting;
279 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
280 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
281 }
282
283 {
284 Mutex::Autolock lock(mCameraStatesLock);
285 mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
286 conflicting));
287 }
288
289 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100290 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100291 mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800292
293 broadcastTorchModeStatus(id, TorchModeStatus::AVAILABLE_OFF);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100294 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800295
296 updateCameraNumAndIds();
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100297 logDeviceAdded(id, "Device added");
298}
299
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100300void CameraService::removeStates(const String8 id) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800301 updateCameraNumAndIds();
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100302 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100303 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100304 mTorchStatusMap.removeItem(id);
305 }
306
307 {
308 Mutex::Autolock lock(mCameraStatesLock);
309 mCameraStates.erase(id);
310 }
311}
312
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800313void CameraService::onDeviceStatusChanged(const String8& id,
314 CameraDeviceStatus newHalStatus) {
315 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
316 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700317
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800318 StatusInternal newStatus = mapToInternal(newHalStatus);
319
Ruben Brunkcc776712015-02-17 20:18:47 -0800320 std::shared_ptr<CameraState> state = getCameraState(id);
321
322 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700323 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100324 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700325 __FUNCTION__, id.string());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100326
327 // First add as absent to make sure clients are notified below
328 addStates(id);
329
330 updateStatus(newStatus, id);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700331 } else {
332 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
333 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700334 return;
335 }
336
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800337 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800338
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800339 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800340 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700341 return;
342 }
343
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800344 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700345 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
346 newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800347
348 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
349 // to this device until the status changes
350 updateStatus(StatusInternal::NOT_PRESENT, id);
351
Ruben Brunkcc776712015-02-17 20:18:47 -0800352 sp<BasicClient> clientToDisconnect;
Igor Murashkincba2c162013-03-20 15:56:31 -0700353 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800354 // Don't do this in updateStatus to avoid deadlock over mServiceLock
355 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700356
Ruben Brunkcc776712015-02-17 20:18:47 -0800357 // Remove cached shim parameters
358 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700359
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700360 // Remove the client from the list of active clients, if there is one
Ruben Brunkcc776712015-02-17 20:18:47 -0800361 clientToDisconnect = removeClientLocked(id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700362 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800363
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700364 // Disconnect client
365 if (clientToDisconnect.get() != nullptr) {
366 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
367 __FUNCTION__, id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800368 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800369 clientToDisconnect->notifyError(
370 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -0800371 CaptureResultExtras{});
Ruben Brunkcc776712015-02-17 20:18:47 -0800372 // Ensure not in binder RPC so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -0700373 LOG_ALWAYS_FATAL_IF(CameraThreadState::getCallingPid() != getpid(),
Ruben Brunkcc776712015-02-17 20:18:47 -0800374 "onDeviceStatusChanged must be called from the camera service process!");
375 clientToDisconnect->disconnect();
Igor Murashkincba2c162013-03-20 15:56:31 -0700376 }
377
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100378 removeStates(id);
Ruben Brunkcc776712015-02-17 20:18:47 -0800379 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800380 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700381 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
382 newStatus));
383 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800384 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700385 }
386
Igor Murashkincba2c162013-03-20 15:56:31 -0700387}
388
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800389void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800390 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800391 Mutex::Autolock al(mTorchStatusMutex);
392 onTorchStatusChangedLocked(cameraId, newStatus);
393}
394
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800395void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800396 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800397 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
398 __FUNCTION__, cameraId.string(), newStatus);
399
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800400 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800401 status_t res = getTorchStatusLocked(cameraId, &status);
402 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700403 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
404 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800405 return;
406 }
407 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800408 return;
409 }
410
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800411 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800412 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800413 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
414 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800415 return;
416 }
417
Ruben Brunkcc776712015-02-17 20:18:47 -0800418 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700419 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700420 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700421 auto iter = mTorchUidMap.find(cameraId);
422 if (iter != mTorchUidMap.end()) {
423 int oldUid = iter->second.second;
424 int newUid = iter->second.first;
425 BatteryNotifier& notifier(BatteryNotifier::getInstance());
426 if (oldUid != newUid) {
427 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800428 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700429 notifier.noteFlashlightOff(cameraId, oldUid);
430 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800431 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700432 notifier.noteFlashlightOn(cameraId, newUid);
433 }
434 iter->second.second = newUid;
435 } else {
436 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800437 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700438 notifier.noteFlashlightOn(cameraId, oldUid);
439 } else {
440 notifier.noteFlashlightOff(cameraId, oldUid);
441 }
442 }
443 }
444 }
445
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800446 broadcastTorchModeStatus(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800447}
448
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800449Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700450 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100451 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700452 switch (type) {
453 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800454 *numCameras = static_cast<int>(mNormalDeviceIds.size());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800455 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700456 case CAMERA_TYPE_ALL:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800457 *numCameras = mNumberOfCameras;
458 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700459 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800460 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700461 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800462 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
463 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700464 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800465 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700466}
467
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800468Status CameraService::getCameraInfo(int cameraId,
469 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700470 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100471 Mutex::Autolock l(mServiceLock);
472
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800473 if (!mInitialized) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800474 return STATUS_ERROR(ERROR_DISCONNECTED,
475 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700476 }
477
Mathias Agopian65ab4712010-07-14 17:59:35 -0700478 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800479 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
480 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700481 }
482
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800483 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800484 status_t err = mCameraProviderManager->getCameraInfo(
485 cameraIdIntToStrLocked(cameraId), cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100486 if (err != OK) {
487 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
488 "Error retrieving camera info from device %d: %s (%d)", cameraId,
489 strerror(-err), err);
Ruben Brunkcc776712015-02-17 20:18:47 -0800490 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100491
Ruben Brunkcc776712015-02-17 20:18:47 -0800492 return ret;
493}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700494
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800495std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
496 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(mNormalDeviceIds.size())) {
497 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
498 __FUNCTION__, cameraIdInt, mNormalDeviceIds.size());
499 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800500 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800501
502 return mNormalDeviceIds[cameraIdInt];
503}
504
505String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
506 Mutex::Autolock lock(mServiceLock);
507 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800508}
509
510Status CameraService::getCameraCharacteristics(const String16& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800511 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700512 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700513 if (!cameraInfo) {
514 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800515 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700516 }
517
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800518 if (!mInitialized) {
519 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800520 return STATUS_ERROR(ERROR_DISCONNECTED,
521 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700522 }
523
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700524 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
525 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
526 "characteristics for system only device %s: ", String8(cameraId).string());
527 }
528
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800529 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800530
Emilian Peevf53f66e2017-04-11 14:29:43 +0100531 status_t res = mCameraProviderManager->getCameraCharacteristics(
532 String8(cameraId).string(), cameraInfo);
533 if (res != OK) {
534 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
535 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
536 strerror(-res), res);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700537 }
Zhijun He2b59be82013-09-25 10:14:30 -0700538
Jayant Chowdhary12361932018-08-27 14:46:13 -0700539 int callingPid = CameraThreadState::getCallingPid();
540 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100541 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700542 // If it's not calling from cameraserver, check the permission only if
543 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
544 // it would've already been checked in shouldRejectSystemCameraConnection.
Emilian Peeve20c6372018-08-14 18:45:53 +0100545 if ((callingPid != getpid()) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700546 (getSystemCameraKind(String8(cameraId)) != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
547 !checkPermission(sCameraPermission, callingPid, callingUid)) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100548 res = cameraInfo->removePermissionEntries(
549 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
550 &tagsRemoved);
551 if (res != OK) {
552 cameraInfo->clear();
553 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
554 " characteristics needing camera permission for device %s: %s (%d)",
555 String8(cameraId).string(), strerror(-res), res);
556 }
557 }
558
559 if (!tagsRemoved.empty()) {
560 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
561 tagsRemoved.data(), tagsRemoved.size());
562 if (res != OK) {
563 cameraInfo->clear();
564 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
565 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
566 strerror(-res), res);
567 }
568 }
569
Zhijun He2b59be82013-09-25 10:14:30 -0700570 return ret;
571}
572
Ruben Brunkcc776712015-02-17 20:18:47 -0800573String8 CameraService::getFormattedCurrentTime() {
574 time_t now = time(nullptr);
575 char formattedTime[64];
576 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
577 return String8(formattedTime);
578}
579
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800580Status CameraService::getCameraVendorTagDescriptor(
581 /*out*/
582 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700583 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800584 if (!mInitialized) {
585 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800586 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800587 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800588 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
589 if (globalDescriptor != nullptr) {
590 *desc = *(globalDescriptor.get());
591 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800592 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800593}
594
Emilian Peev71c73a22017-03-21 16:35:51 +0000595Status CameraService::getCameraVendorTagCache(
596 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
597 ATRACE_CALL();
598 if (!mInitialized) {
599 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
600 return STATUS_ERROR(ERROR_DISCONNECTED,
601 "Camera subsystem not available");
602 }
603 sp<VendorTagDescriptorCache> globalCache =
604 VendorTagDescriptorCache::getGlobalVendorTagCache();
605 if (globalCache != nullptr) {
606 *cache = *(globalCache.get());
607 }
608 return Status::ok();
609}
610
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800611int CameraService::getDeviceVersion(const String8& cameraId, int* facing) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700612 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800613
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800614 int deviceVersion = 0;
615
Emilian Peevf53f66e2017-04-11 14:29:43 +0100616 status_t res;
617 hardware::hidl_version maxVersion{0,0};
618 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
619 &maxVersion);
620 if (res != OK) return -1;
621 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800622
Emilian Peevf53f66e2017-04-11 14:29:43 +0100623 hardware::CameraInfo info;
624 if (facing) {
625 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800626 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100627 *facing = info.facing;
Igor Murashkin634a5152013-02-20 17:15:11 -0800628 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100629
Igor Murashkin634a5152013-02-20 17:15:11 -0800630 return deviceVersion;
631}
632
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800633Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700634 switch(err) {
635 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800636 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800637 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800638 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
639 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800640 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800641 return STATUS_ERROR(ERROR_DISCONNECTED,
642 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700643 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800644 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
645 "Camera HAL encountered error %d: %s",
646 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700647 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800648}
649
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800650Status CameraService::makeClient(const sp<CameraService>& cameraService,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800651 const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800652 int api1CameraId, int facing, int clientPid, uid_t clientUid, int servicePid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700653 int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
Ruben Brunkcc776712015-02-17 20:18:47 -0800654 /*out*/sp<BasicClient>* client) {
655
Ruben Brunkcc776712015-02-17 20:18:47 -0800656 if (halVersion < 0 || halVersion == deviceVersion) {
657 // Default path: HAL version is unspecified by caller, create CameraClient
658 // based on device version reported by the HAL.
659 switch(deviceVersion) {
660 case CAMERA_DEVICE_API_VERSION_1_0:
661 if (effectiveApiLevel == API_1) { // Camera1 API route
662 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800663 *client = new CameraClient(cameraService, tmp, packageName,
664 api1CameraId, facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700665 getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800666 } else { // Camera2 API route
667 ALOGW("Camera using old HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800668 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800669 "Camera device \"%s\" HAL version %d does not support camera2 API",
670 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800671 }
672 break;
Ruben Brunkcc776712015-02-17 20:18:47 -0800673 case CAMERA_DEVICE_API_VERSION_3_0:
674 case CAMERA_DEVICE_API_VERSION_3_1:
675 case CAMERA_DEVICE_API_VERSION_3_2:
676 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -0700677 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -0700678 case CAMERA_DEVICE_API_VERSION_3_5:
Ruben Brunkcc776712015-02-17 20:18:47 -0800679 if (effectiveApiLevel == API_1) { // Camera1 API route
680 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800681 *client = new Camera2Client(cameraService, tmp, packageName,
682 cameraId, api1CameraId,
683 facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700684 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800685 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800686 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
687 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
688 *client = new CameraDeviceClient(cameraService, tmp, packageName, cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -0800689 facing, clientPid, clientUid, servicePid);
690 }
691 break;
692 default:
693 // Should not be reachable
694 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800695 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800696 "Camera device \"%s\" has unknown HAL version %d",
697 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800698 }
699 } else {
700 // A particular HAL version is requested by caller. Create CameraClient
701 // based on the requested HAL version.
702 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
703 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
704 // Only support higher HAL version device opened as HAL1.0 device.
705 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800706 *client = new CameraClient(cameraService, tmp, packageName,
707 api1CameraId, facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700708 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800709 } else {
710 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
711 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
712 " opened as HAL %x device", halVersion, deviceVersion,
713 CAMERA_DEVICE_API_VERSION_1_0);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800714 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800715 "Camera device \"%s\" (HAL version %d) cannot be opened as HAL version %d",
716 cameraId.string(), deviceVersion, halVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800717 }
718 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800719 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800720}
721
Ruben Brunk6267b532015-04-30 17:44:07 -0700722String8 CameraService::toString(std::set<userid_t> intSet) {
723 String8 s("");
724 bool first = true;
725 for (userid_t i : intSet) {
726 if (first) {
727 s.appendFormat("%d", i);
728 first = false;
729 } else {
730 s.appendFormat(", %d", i);
731 }
732 }
733 return s;
734}
735
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800736int32_t CameraService::mapToInterface(TorchModeStatus status) {
737 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
738 switch (status) {
739 case TorchModeStatus::NOT_AVAILABLE:
740 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
741 break;
742 case TorchModeStatus::AVAILABLE_OFF:
743 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
744 break;
745 case TorchModeStatus::AVAILABLE_ON:
746 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
747 break;
748 default:
749 ALOGW("Unknown new flash status: %d", status);
750 }
751 return serviceStatus;
752}
753
754CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
755 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
756 switch (status) {
757 case CameraDeviceStatus::NOT_PRESENT:
758 serviceStatus = StatusInternal::NOT_PRESENT;
759 break;
760 case CameraDeviceStatus::PRESENT:
761 serviceStatus = StatusInternal::PRESENT;
762 break;
763 case CameraDeviceStatus::ENUMERATING:
764 serviceStatus = StatusInternal::ENUMERATING;
765 break;
766 default:
767 ALOGW("Unknown new HAL device status: %d", status);
768 }
769 return serviceStatus;
770}
771
772int32_t CameraService::mapToInterface(StatusInternal status) {
773 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
774 switch (status) {
775 case StatusInternal::NOT_PRESENT:
776 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
777 break;
778 case StatusInternal::PRESENT:
779 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
780 break;
781 case StatusInternal::ENUMERATING:
782 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
783 break;
784 case StatusInternal::NOT_AVAILABLE:
785 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
786 break;
787 case StatusInternal::UNKNOWN:
788 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
789 break;
790 default:
791 ALOGW("Unknown new internal device status: %d", status);
792 }
793 return serviceStatus;
794}
795
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800796Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -0700797 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700798
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800799 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -0800800 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800801 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800802 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800803 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800804 sp<ICameraClient>{nullptr}, id, cameraId,
805 static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800806 internalPackageName, uid, USE_CALLING_PID,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700807 API_1, /*shimUpdateOnly*/ true, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800808 ).isOk()) {
809 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -0700810 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800811 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700812}
813
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800814Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -0700815 /*out*/
816 CameraParameters* parameters) {
817
818 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
819
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800820 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -0700821
822 if (parameters == NULL) {
823 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800824 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700825 }
826
Ruben Brunkcc776712015-02-17 20:18:47 -0800827 String8 id = String8::format("%d", cameraId);
828
829 // Check if we already have parameters
830 {
831 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700832 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800833 auto cameraState = getCameraState(id);
834 if (cameraState == nullptr) {
835 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800836 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
837 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800838 }
839 CameraParameters p = cameraState->getShimParams();
840 if (!p.isEmpty()) {
841 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800842 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700843 }
844 }
845
Jayant Chowdhary12361932018-08-27 14:46:13 -0700846 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -0800847 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -0700848 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800849 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800850 // Error already logged by callee
851 return ret;
852 }
853
854 // Check for parameters again
855 {
856 // Scope for service lock
857 Mutex::Autolock lock(mServiceLock);
858 auto cameraState = getCameraState(id);
859 if (cameraState == nullptr) {
860 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800861 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
862 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -0700863 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800864 CameraParameters p = cameraState->getShimParams();
865 if (!p.isEmpty()) {
866 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800867 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700868 }
869 }
870
Ruben Brunkcc776712015-02-17 20:18:47 -0800871 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
872 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800873 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700874}
875
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800876// Can camera service trust the caller based on the calling UID?
877static bool isTrustedCallingUid(uid_t uid) {
878 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -0700879 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800880 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -0700881 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800882 return true;
883 default:
884 return false;
885 }
886}
887
Nicholas Sauera3620332019-04-03 14:05:17 -0700888static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
889 PermissionController pc;
890 uid = pc.getPackageUid(packageName, 0);
891 if (uid <= 0) {
892 ALOGE("Unknown package: '%s'", String8(packageName).string());
893 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
894 return BAD_VALUE;
895 }
896
897 if (userId < 0) {
898 ALOGE("Invalid user: %d", userId);
899 dprintf(err, "Invalid user: %d\n", userId);
900 return BAD_VALUE;
901 }
902
903 uid = multiuser_get_uid(userId, uid);
904 return NO_ERROR;
905}
906
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800907Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -0700908 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
909 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -0500910
Alex Deymo9c2a2c22016-08-25 11:59:14 -0700911#ifdef __BRILLO__
912 UNUSED(clientName8);
913 UNUSED(clientUid);
914 UNUSED(clientPid);
915 UNUSED(originalClientPid);
916#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -0700917 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
918 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800919 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -0800920 return allowed;
921 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -0700922#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -0800923
Jayant Chowdhary12361932018-08-27 14:46:13 -0700924 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800925
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800926 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800927 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
928 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800929 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
930 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -0700931 }
932
Ruben Brunkcc776712015-02-17 20:18:47 -0800933 if (getCameraState(cameraId) == nullptr) {
934 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
935 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800936 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
937 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700938 }
939
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800940 status_t err = checkIfDeviceIsUsable(cameraId);
941 if (err != NO_ERROR) {
942 switch(err) {
943 case -ENODEV:
944 case -EBUSY:
945 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
946 "No camera device with ID \"%s\" currently available", cameraId.string());
947 default:
948 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
949 "Unknown error connecting to ID \"%s\"", cameraId.string());
950 }
951 }
952 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -0800953}
954
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800955Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -0700956 const String8& clientName8, int& clientUid, int& clientPid,
957 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -0700958 int callingPid = CameraThreadState::getCallingPid();
959 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700960
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800961 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -0700962 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800963 clientUid = callingUid;
964 } else if (!isTrustedCallingUid(callingUid)) {
965 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
966 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800967 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
968 "Untrusted caller (calling PID %d, UID %d) trying to "
969 "forward camera access to camera %s for client %s (PID %d, UID %d)",
970 callingPid, callingUid, cameraId.string(),
971 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700972 }
973
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800974 // Check if we can trust clientPid
975 if (clientPid == USE_CALLING_PID) {
976 clientPid = callingPid;
977 } else if (!isTrustedCallingUid(callingUid)) {
978 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
979 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800980 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
981 "Untrusted caller (calling PID %d, UID %d) trying to "
982 "forward camera access to camera %s for client %s (PID %d, UID %d)",
983 callingPid, callingUid, cameraId.string(),
984 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800985 }
986
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700987 if (shouldRejectSystemCameraConnection(cameraId)) {
988 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
989 cameraId.c_str());
990 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
991 "available", cameraId.string());
992 }
993 // If it's not calling from cameraserver, check the permission if the
994 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
995 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800996 if (callingPid != getpid() &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700997 (getSystemCameraKind(cameraId) != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
998 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800999 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001000 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1001 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1002 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001003 }
1004
Svet Ganova453d0d2018-01-11 15:37:58 -08001005 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001006 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001007 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001008 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1009 clientPid, clientUid);
1010 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001011 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1012 "calling UID %d proc state %" PRId32 ")",
1013 clientName8.string(), clientUid, clientPid, cameraId.string(),
1014 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001015 }
1016
Michael Grooverd1d435a2018-12-18 17:39:42 -08001017 // If sensor privacy is enabled then prevent access to the camera
1018 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1019 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1020 return STATUS_ERROR_FMT(ERROR_DISABLED,
1021 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1022 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1023 }
1024
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001025 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1026 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001027 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001028 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001029
Ruben Brunk6267b532015-04-30 17:44:07 -07001030 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001031
Ruben Brunka8ca9152015-04-07 14:23:40 -07001032 // Only allow clients who are being used by the current foreground device user, unless calling
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001033 // from our own process OR the caller is using the cameraserver's HIDL interface.
1034 if (!hardware::IPCThreadState::self()->isServingCall() && callingPid != getpid() &&
1035 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001036 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1037 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1038 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001039 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1040 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1041 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001042 }
1043
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001044 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001045}
1046
1047status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1048 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001049 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001050 if (cameraState == nullptr) {
1051 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1052 cameraId.string());
1053 return -ENODEV;
1054 }
1055
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001056 StatusInternal currentStatus = cameraState->getStatus();
1057 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001058 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1059 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001060 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001061 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001062 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1063 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001064 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001065 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001066
Ruben Brunkcc776712015-02-17 20:18:47 -08001067 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001068}
1069
Ruben Brunkcc776712015-02-17 20:18:47 -08001070void CameraService::finishConnectLocked(const sp<BasicClient>& client,
1071 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001072
Ruben Brunkcc776712015-02-17 20:18:47 -08001073 // Make a descriptor for the incoming client
1074 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
1075 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1076
1077 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1078 String8(client->getPackageName()));
1079
1080 if (evicted.size() > 0) {
1081 // This should never happen - clients should already have been removed in disconnect
1082 for (auto& i : evicted) {
1083 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1084 __FUNCTION__, i->getKey().string());
1085 }
1086
1087 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1088 __FUNCTION__);
1089 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001090
1091 // And register a death notification for the client callback. Do
1092 // this last to avoid Binder policy where a nested Binder
1093 // transaction might be pre-empted to service the client death
1094 // notification if the client process dies before linkToDeath is
1095 // invoked.
1096 sp<IBinder> remoteCallback = client->getRemote();
1097 if (remoteCallback != nullptr) {
1098 remoteCallback->linkToDeath(this);
1099 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001100}
1101
1102status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1103 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
1104 /*out*/
1105 sp<BasicClient>* client,
1106 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001107 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001108 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001109 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001110 DescriptorPtr clientDescriptor;
1111 {
1112 if (effectiveApiLevel == API_1) {
1113 // If we are using API1, any existing client for this camera ID with the same remote
1114 // should be returned rather than evicted to allow MediaRecorder to work properly.
1115
1116 auto current = mActiveClientManager.get(cameraId);
1117 if (current != nullptr) {
1118 auto clientSp = current->getValue();
1119 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001120 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1121 ALOGW("CameraService connect called from same client, but with a different"
1122 " API level, evicting prior client...");
1123 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001124 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001125 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001126 *client = clientSp;
1127 return NO_ERROR;
1128 }
1129 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001130 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001131 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001132
Ruben Brunkcc776712015-02-17 20:18:47 -08001133 // Get current active client PIDs
1134 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1135 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001136
Emilian Peev8131a262017-02-01 12:33:43 +00001137 std::vector<int> priorityScores(ownerPids.size());
1138 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001139
Emilian Peev8131a262017-02-01 12:33:43 +00001140 // Get priority scores of all active PIDs
1141 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1142 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1143 /*out*/&priorityScores[0]);
1144 if (err != OK) {
1145 ALOGE("%s: Priority score query failed: %d",
1146 __FUNCTION__, err);
1147 return err;
1148 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001149
Ruben Brunkcc776712015-02-17 20:18:47 -08001150 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001151 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001152 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001153 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001154 resource_policy::ClientPriority(priorityScores[i], states[i],
1155 /* isVendorClient won't get copied over*/ false));
Ruben Brunkcc776712015-02-17 20:18:47 -08001156 }
1157 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001158
Ruben Brunkcc776712015-02-17 20:18:47 -08001159 // Get state for the given cameraId
1160 auto state = getCameraState(cameraId);
1161 if (state == nullptr) {
1162 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1163 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001164 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001165 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001166 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001167
1168 // Make descriptor for incoming client
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001169 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001170 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1171 state->getConflicting(),
Emilian Peev8131a262017-02-01 12:33:43 +00001172 priorityScores[priorityScores.size() - 1],
1173 clientPid,
1174 states[states.size() - 1]);
Ruben Brunkcc776712015-02-17 20:18:47 -08001175
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001176 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1177
Ruben Brunkcc776712015-02-17 20:18:47 -08001178 // Find clients that would be evicted
1179 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1180
1181 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1182 // background, so we cannot do evictions
1183 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1184 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1185 " priority).", clientPid);
1186
1187 sp<BasicClient> clientSp = clientDescriptor->getValue();
1188 String8 curTime = getFormattedCurrentTime();
1189 auto incompatibleClients =
1190 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1191
1192 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001193 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001194 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001195 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001196
1197 for (auto& i : incompatibleClients) {
1198 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001199 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1200 i->getKey().string(),
1201 String8{i->getValue()->getPackageName()}.string(),
1202 i->getOwnerId(), i->getPriority().getScore(),
1203 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001204 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001205 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001206 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001207 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001208 }
1209
1210 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001211 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001212 mEventLog.add(msg);
1213
1214 return -EBUSY;
1215 }
1216
1217 for (auto& i : evicted) {
1218 sp<BasicClient> clientSp = i->getValue();
1219 if (clientSp.get() == nullptr) {
1220 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1221
1222 // TODO: Remove this
1223 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1224 __FUNCTION__);
1225 mActiveClientManager.remove(i);
1226 continue;
1227 }
1228
1229 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1230 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001231 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001232
Ruben Brunkcc776712015-02-17 20:18:47 -08001233 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001234 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001235 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1236 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001237 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001238 i->getOwnerId(), i->getPriority().getScore(),
1239 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001240 packageName.string(), clientPid, clientPriority.getScore(),
1241 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001242
1243 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001244 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001245 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001246 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001247 }
1248
Ruben Brunkcc776712015-02-17 20:18:47 -08001249 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1250 // other clients from connecting in mServiceLockWrapper if held
1251 mServiceLock.unlock();
1252
1253 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001254 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001255
1256 // Destroy evicted clients
1257 for (auto& i : evictedClients) {
1258 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001259 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001260 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001261
Jayant Chowdhary12361932018-08-27 14:46:13 -07001262 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001263
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001264 for (const auto& i : evictedClients) {
1265 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1266 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1267 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1268 if (ret == TIMED_OUT) {
1269 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1270 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1271 mActiveClientManager.toString().string());
1272 return -EBUSY;
1273 }
1274 if (ret != NO_ERROR) {
1275 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1276 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1277 ret, mActiveClientManager.toString().string());
1278 return ret;
1279 }
1280 }
1281
1282 evictedClients.clear();
1283
Ruben Brunkcc776712015-02-17 20:18:47 -08001284 // Once clients have been disconnected, relock
1285 mServiceLock.lock();
1286
1287 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1288 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1289 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001290 }
1291
Ruben Brunkcc776712015-02-17 20:18:47 -08001292 *partial = clientDescriptor;
1293 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001294}
1295
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001296Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001297 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001298 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001299 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001300 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001301 int clientPid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001302 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001303 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001304
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001305 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001306 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001307
1308 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001309 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001310 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001311 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, clientUid, clientPid, API_1,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001312 /*shimUpdateOnly*/ false, /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001313
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001314 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001315 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001316 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001317 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001318 }
1319
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001320 *device = client;
1321 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001322}
1323
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001324Status CameraService::connectLegacy(
Zhijun Heb10cdad2014-06-16 16:38:35 -07001325 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001326 int api1CameraId, int halVersion,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001327 const String16& clientPackageName,
Zhijun Heb10cdad2014-06-16 16:38:35 -07001328 int clientUid,
1329 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001330 sp<ICamera>* device) {
Zhijun Heb10cdad2014-06-16 16:38:35 -07001331
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001332 ATRACE_CALL();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001333 String8 id = cameraIdIntToStr(api1CameraId);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001334
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001335 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001336 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001337 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId, halVersion,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001338 clientPackageName, clientUid, USE_CALLING_PID, API_1, /*shimUpdateOnly*/ false,
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001339 /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001340
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001341 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001342 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001343 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001344 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001345 }
1346
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001347 *device = client;
1348 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001349}
1350
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001351static bool hasPermissionsForSystemCamera(int callingPid, int callingUid) {
1352 return checkPermission(sSystemCameraPermission, callingPid, callingUid) &&
1353 checkPermission(sCameraPermission, callingPid, callingUid);
1354}
1355
1356bool CameraService::shouldSkipStatusUpdates(const String8& cameraId, bool isVendorListener,
1357 int clientPid, int clientUid) const {
1358 SystemCameraKind systemCameraKind = getSystemCameraKind(cameraId);
1359 // If the client is not a vendor client, don't add listener if
1360 // a) the camera is a publicly hidden secure camera OR
1361 // b) the camera is a system only camera and the client doesn't
1362 // have android.permission.SYSTEM_CAMERA permissions.
1363 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1364 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1365 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001366 return true;
1367 }
1368 return false;
1369}
1370
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001371bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1372 // Rules for rejection:
1373 // 1) If cameraserver tries to access this camera device, accept the
1374 // connection.
1375 // 2) The camera device is a publicly hidden secure camera device AND some
1376 // component is trying to access it on a non-hwbinder thread (generally a non HAL client),
1377 // reject it.
1378 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1379 // and the serving thread is a non hwbinder thread, the client must have
1380 // android.permission.SYSTEM_CAMERA permissions to connect.
1381
1382 int cPid = CameraThreadState::getCallingPid();
1383 int cUid = CameraThreadState::getCallingUid();
1384 SystemCameraKind systemCameraKind = getSystemCameraKind(cameraId);
1385
1386 // (1) Cameraserver trying to connect, accept.
1387 if (CameraThreadState::getCallingPid() == getpid()) {
1388 return false;
1389 }
1390 // (2)
1391 if (!hardware::IPCThreadState::self()->isServingCall() &&
1392 systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
1393 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1394 return true;
1395 }
1396 // (3) Here we only check for permissions if it is a system only camera device. This is since
1397 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1398 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1399 // same behavior for system camera devices.
1400 if (!hardware::IPCThreadState::self()->isServingCall() &&
1401 systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1402 !hasPermissionsForSystemCamera(cPid, cUid)) {
1403 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1404 cameraId.c_str());
1405 return true;
1406 }
1407
1408 return false;
1409}
1410
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001411Status CameraService::connectDevice(
1412 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001413 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001414 const String16& clientPackageName,
Ruben Brunkcc776712015-02-17 20:18:47 -08001415 int clientUid,
1416 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001417 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001418
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001419 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001420 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001421 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001422 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001423 String16 clientPackageNameAdj = clientPackageName;
1424 if (hardware::IPCThreadState::self()->isServingCall()) {
1425 std::string vendorClient =
1426 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1427 clientPackageNameAdj = String16(vendorClient.c_str());
1428 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001429 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001430 /*api1CameraId*/-1,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001431 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageNameAdj,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001432 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001433
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001434 if(!ret.isOk()) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001435 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageNameAdj),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001436 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001437 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001438 }
1439
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001440 *device = client;
1441 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001442}
1443
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001444template<class CALLBACK, class CLIENT>
1445Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001446 int api1CameraId, int halVersion, const String16& clientPackageName, int clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001447 int clientPid, apiLevel effectiveApiLevel, bool shimUpdateOnly,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001448 /*out*/sp<CLIENT>& device) {
1449 binder::Status ret = binder::Status::ok();
1450
1451 String8 clientName8(clientPackageName);
1452
1453 int originalClientPid = 0;
1454
1455 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) for HAL version %s and "
1456 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
1457 (halVersion == -1) ? "default" : std::to_string(halVersion).c_str(),
1458 static_cast<int>(effectiveApiLevel));
1459
1460 sp<CLIENT> client = nullptr;
1461 {
1462 // Acquire mServiceLock and prevent other clients from connecting
1463 std::unique_ptr<AutoConditionLock> lock =
1464 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1465
1466 if (lock == nullptr) {
1467 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1468 , clientPid);
1469 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1470 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1471 cameraId.string(), clientName8.string(), clientPid);
1472 }
1473
1474 // Enforce client permissions and do basic sanity checks
1475 if(!(ret = validateConnectLocked(cameraId, clientName8,
1476 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1477 return ret;
1478 }
1479
1480 // Check the shim parameters after acquiring lock, if they have already been updated and
1481 // we were doing a shim update, return immediately
1482 if (shimUpdateOnly) {
1483 auto cameraState = getCameraState(cameraId);
1484 if (cameraState != nullptr) {
1485 if (!cameraState->getShimParams().isEmpty()) return ret;
1486 }
1487 }
1488
1489 status_t err;
1490
1491 sp<BasicClient> clientTmp = nullptr;
1492 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1493 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
1494 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
1495 /*out*/&partial)) != NO_ERROR) {
1496 switch (err) {
1497 case -ENODEV:
1498 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1499 "No camera device with ID \"%s\" currently available",
1500 cameraId.string());
1501 case -EBUSY:
1502 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1503 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1504 cameraId.string());
1505 default:
1506 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1507 "Unexpected error %s (%d) opening camera \"%s\"",
1508 strerror(-err), err, cameraId.string());
1509 }
1510 }
1511
1512 if (clientTmp.get() != nullptr) {
1513 // Handle special case for API1 MediaRecorder where the existing client is returned
1514 device = static_cast<CLIENT*>(clientTmp.get());
1515 return ret;
1516 }
1517
1518 // give flashlight a chance to close devices if necessary.
1519 mFlashlight->prepareDeviceOpen(cameraId);
1520
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001521 int facing = -1;
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001522 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001523 if (facing == -1) {
1524 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1525 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1526 "Unable to get camera device \"%s\" facing", cameraId.string());
1527 }
1528
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001529 sp<BasicClient> tmp = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001530 if(!(ret = makeClient(this, cameraCb, clientPackageName,
1531 cameraId, api1CameraId, facing,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001532 clientPid, clientUid, getpid(),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001533 halVersion, deviceVersion, effectiveApiLevel,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001534 /*out*/&tmp)).isOk()) {
1535 return ret;
1536 }
1537 client = static_cast<CLIENT*>(tmp.get());
1538
1539 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1540 __FUNCTION__);
1541
Emilian Peevbd8c5032018-02-14 23:05:40 +00001542 err = client->initialize(mCameraProviderManager, mMonitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001543 if (err != OK) {
1544 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001545 // Errors could be from the HAL module open call or from AppOpsManager
1546 switch(err) {
1547 case BAD_VALUE:
1548 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1549 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1550 case -EBUSY:
1551 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1552 "Camera \"%s\" is already open", cameraId.string());
1553 case -EUSERS:
1554 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1555 "Too many cameras already open, cannot open camera \"%s\"",
1556 cameraId.string());
1557 case PERMISSION_DENIED:
1558 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1559 "No permission to open camera \"%s\"", cameraId.string());
1560 case -EACCES:
1561 return STATUS_ERROR_FMT(ERROR_DISABLED,
1562 "Camera \"%s\" disabled by policy", cameraId.string());
1563 case -ENODEV:
1564 default:
1565 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1566 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1567 strerror(-err), err);
1568 }
1569 }
1570
1571 // Update shim paremeters for legacy clients
1572 if (effectiveApiLevel == API_1) {
1573 // Assume we have always received a Client subclass for API1
1574 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1575 String8 rawParams = shimClient->getParameters();
1576 CameraParameters params(rawParams);
1577
1578 auto cameraState = getCameraState(cameraId);
1579 if (cameraState != nullptr) {
1580 cameraState->setShimParams(params);
1581 } else {
1582 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1583 __FUNCTION__, cameraId.string());
1584 }
1585 }
1586
1587 if (shimUpdateOnly) {
1588 // If only updating legacy shim parameters, immediately disconnect client
1589 mServiceLock.unlock();
1590 client->disconnect();
1591 mServiceLock.lock();
1592 } else {
1593 // Otherwise, add client to active clients list
1594 finishConnectLocked(client, partial);
1595 }
1596 } // lock is destroyed, allow further connect calls
1597
1598 // Important: release the mutex here so the client can call back into the service from its
1599 // destructor (can be at the end of the call)
1600 device = client;
1601 return ret;
1602}
1603
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001604Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001605 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001606 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001607
1608 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001609 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001610 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001611 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1612 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001613 }
1614
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001615 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07001616 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001617
1618 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001619 auto state = getCameraState(id);
1620 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001621 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001622 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1623 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001624 }
1625
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001626 StatusInternal cameraStatus = state->getStatus();
1627 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001628 cameraStatus != StatusInternal::NOT_AVAILABLE) {
1629 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001630 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1631 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001632 }
1633
1634 {
1635 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001636 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001637 status_t err = getTorchStatusLocked(id, &status);
1638 if (err != OK) {
1639 if (err == NAME_NOT_FOUND) {
1640 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1641 "Camera \"%s\" does not have a flash unit", id.string());
1642 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001643 ALOGE("%s: getting current torch status failed for camera %s",
1644 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001645 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1646 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
1647 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001648 }
1649
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001650 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001651 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001652 ALOGE("%s: torch mode of camera %s is not available because "
1653 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001654 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1655 "Torch for camera \"%s\" is not available due to an existing camera user",
1656 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001657 } else {
1658 ALOGE("%s: torch mode of camera %s is not available due to "
1659 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001660 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1661 "Torch for camera \"%s\" is not available due to insufficient resources",
1662 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001663 }
1664 }
1665 }
1666
Ruben Brunk99e69712015-05-26 17:25:07 -07001667 {
1668 // Update UID map - this is used in the torch status changed callbacks, so must be done
1669 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001670 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001671 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1672 mTorchUidMap[id].first = uid;
1673 mTorchUidMap[id].second = uid;
1674 } else {
1675 // Set the pending UID
1676 mTorchUidMap[id].first = uid;
1677 }
1678 }
1679
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001680 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001681
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001682 if (err != OK) {
1683 int32_t errorCode;
1684 String8 msg;
1685 switch (err) {
1686 case -ENOSYS:
1687 msg = String8::format("Camera \"%s\" has no flashlight",
1688 id.string());
1689 errorCode = ERROR_ILLEGAL_ARGUMENT;
1690 break;
1691 default:
1692 msg = String8::format(
1693 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1694 id.string(), enabled, strerror(-err), err);
1695 errorCode = ERROR_INVALID_OPERATION;
1696 }
1697 ALOGE("%s: %s", __FUNCTION__, msg.string());
1698 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001699 }
1700
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001701 {
1702 // update the link to client's death
1703 Mutex::Autolock al(mTorchClientMapMutex);
1704 ssize_t index = mTorchClientMap.indexOfKey(id);
1705 if (enabled) {
1706 if (index == NAME_NOT_FOUND) {
1707 mTorchClientMap.add(id, clientBinder);
1708 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001709 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001710 mTorchClientMap.replaceValueAt(index, clientBinder);
1711 }
1712 clientBinder->linkToDeath(this);
1713 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001714 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001715 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001716 }
1717
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07001718 int clientPid = CameraThreadState::getCallingPid();
1719 const char *id_cstr = id.c_str();
1720 const char *torchState = enabled ? "on" : "off";
1721 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
1722 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001723 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001724}
1725
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001726Status CameraService::notifySystemEvent(int32_t eventId,
1727 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001728 const int pid = CameraThreadState::getCallingPid();
1729 const int selfPid = getpid();
1730
1731 // Permission checks
1732 if (pid != selfPid) {
1733 // Ensure we're being called by system_server, or similar process with
1734 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001735 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001736 const int uid = CameraThreadState::getCallingUid();
1737 ALOGE("Permission Denial: cannot send updates to camera service about system"
1738 " events from pid=%d, uid=%d", pid, uid);
1739 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09001740 "No permission to send updates to camera service about system events"
1741 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001742 }
1743 }
1744
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001745 ATRACE_CALL();
1746
Ruben Brunk36597b22015-03-20 22:15:57 -07001747 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001748 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001749 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07001750 // from a system server crash
1751 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08001752 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001753 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07001754 break;
1755 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001756 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07001757 default: {
1758 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1759 eventId);
1760 break;
1761 }
1762 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001763 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07001764}
1765
Emilian Peev53722fa2019-02-22 17:47:20 -08001766void CameraService::notifyMonitoredUids() {
1767 Mutex::Autolock lock(mStatusListenerLock);
1768
1769 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001770 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08001771 if (!ret.isOk()) {
1772 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
1773 ret.exceptionCode());
1774 }
1775 }
1776}
1777
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08001778Status CameraService::notifyDeviceStateChange(int64_t newState) {
1779 const int pid = CameraThreadState::getCallingPid();
1780 const int selfPid = getpid();
1781
1782 // Permission checks
1783 if (pid != selfPid) {
1784 // Ensure we're being called by system_server, or similar process with
1785 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001786 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08001787 const int uid = CameraThreadState::getCallingUid();
1788 ALOGE("Permission Denial: cannot send updates to camera service about device"
1789 " state changes from pid=%d, uid=%d", pid, uid);
1790 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1791 "No permission to send updates to camera service about device state"
1792 " changes from pid=%d, uid=%d", pid, uid);
1793 }
1794 }
1795
1796 ATRACE_CALL();
1797
1798 using hardware::camera::provider::V2_5::DeviceState;
1799 hardware::hidl_bitfield<DeviceState> newDeviceState{};
1800 if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
1801 newDeviceState |= DeviceState::BACK_COVERED;
1802 }
1803 if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
1804 newDeviceState |= DeviceState::FRONT_COVERED;
1805 }
1806 if (newState & ICameraService::DEVICE_STATE_FOLDED) {
1807 newDeviceState |= DeviceState::FOLDED;
1808 }
1809 // Only map vendor bits directly
1810 uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
1811 newDeviceState |= vendorBits;
1812
1813 ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
1814 Mutex::Autolock l(mServiceLock);
1815 mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
1816
1817 return Status::ok();
1818}
1819
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001820Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
1821 /*out*/
1822 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001823 return addListenerHelper(listener, cameraStatuses);
1824}
1825
1826Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
1827 /*out*/
1828 std::vector<hardware::CameraStatus> *cameraStatuses,
1829 bool isVendorListener) {
1830
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001831 ATRACE_CALL();
1832
Igor Murashkinbfc99152013-02-27 12:55:20 -08001833 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08001834
Ruben Brunk3450ba72015-06-16 11:00:37 -07001835 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001836 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001837 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001838 }
1839
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001840 auto clientUid = CameraThreadState::getCallingUid();
1841 auto clientPid = CameraThreadState::getCallingPid();
1842
Igor Murashkinbfc99152013-02-27 12:55:20 -08001843 Mutex::Autolock lock(mServiceLock);
1844
Ruben Brunkcc776712015-02-17 20:18:47 -08001845 {
1846 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08001847 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001848 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001849 ALOGW("%s: Tried to add listener %p which was already subscribed",
1850 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001851 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08001852 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001853 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001854
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001855 sp<ServiceListener> serviceListener =
1856 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08001857 auto ret = serviceListener->initialize();
1858 if (ret != NO_ERROR) {
1859 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
1860 strerror(-ret), ret);
1861 ALOGE("%s: %s", __FUNCTION__, msg.string());
1862 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
1863 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001864 // The listener still needs to be added to the list of listeners, regardless of what
1865 // permissions the listener process has / whether it is a vendor listener. Since it might be
1866 // eligible to listen to other camera ids.
1867 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08001868 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08001869 }
1870
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001871 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07001872 {
Ruben Brunkcc776712015-02-17 20:18:47 -08001873 Mutex::Autolock lock(mCameraStatesLock);
1874 for (auto& i : mCameraStates) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001875 if (shouldSkipStatusUpdates(i.first, isVendorListener, clientPid, clientUid)) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001876 ALOGV("Cannot add public listener for hidden system-only %s for pid %d",
1877 i.first.c_str(), CameraThreadState::getCallingPid());
1878 continue;
1879 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001880 cameraStatuses->emplace_back(i.first, mapToInterface(i.second->getStatus()));
Igor Murashkincba2c162013-03-20 15:56:31 -07001881 }
1882 }
1883
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001884 /*
1885 * Immediately signal current torch status to this listener only
1886 * This may be a subset of all the devices, so don't include it in the response directly
1887 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001888 {
1889 Mutex::Autolock al(mTorchStatusMutex);
1890 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001891 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001892 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001893 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001894 }
1895
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001896 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08001897}
Ruben Brunkcc776712015-02-17 20:18:47 -08001898
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001899Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001900 ATRACE_CALL();
1901
Igor Murashkinbfc99152013-02-27 12:55:20 -08001902 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
1903
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001904 if (listener == 0) {
1905 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001906 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001907 }
1908
Igor Murashkinbfc99152013-02-27 12:55:20 -08001909 Mutex::Autolock lock(mServiceLock);
1910
Ruben Brunkcc776712015-02-17 20:18:47 -08001911 {
1912 Mutex::Autolock lock(mStatusListenerLock);
1913 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001914 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
1915 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
1916 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08001917 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001918 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001919 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001920 }
1921 }
1922
1923 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
1924 __FUNCTION__, listener.get());
1925
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001926 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08001927}
1928
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001929Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001930
1931 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001932 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1933
1934 if (parameters == NULL) {
1935 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001936 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001937 }
1938
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001939 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001940
1941 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001942 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07001943 // Error logged by caller
1944 return ret;
1945 }
1946
1947 String8 shimParamsString8 = shimParams.flatten();
1948 String16 shimParamsString16 = String16(shimParamsString8);
1949
1950 *parameters = shimParamsString16;
1951
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001952 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001953}
1954
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001955Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
1956 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001957 ATRACE_CALL();
1958
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001959 const String8 id = String8(cameraId);
1960
1961 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001962
1963 switch (apiVersion) {
1964 case API_VERSION_1:
1965 case API_VERSION_2:
1966 break;
1967 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001968 String8 msg = String8::format("Unknown API version %d", apiVersion);
1969 ALOGE("%s: %s", __FUNCTION__, msg.string());
1970 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001971 }
1972
Emilian Peev28ad2ea2017-02-07 16:14:32 +00001973 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07001974 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001975 case CAMERA_DEVICE_API_VERSION_1_0:
1976 case CAMERA_DEVICE_API_VERSION_3_0:
1977 case CAMERA_DEVICE_API_VERSION_3_1:
1978 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001979 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
1980 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001981 *isSupported = false;
1982 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001983 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
1984 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001985 *isSupported = true;
1986 }
1987 break;
1988 case CAMERA_DEVICE_API_VERSION_3_2:
1989 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07001990 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07001991 case CAMERA_DEVICE_API_VERSION_3_5:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001992 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
1993 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001994 *isSupported = true;
1995 break;
1996 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001997 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001998 ALOGE("%s: %s", __FUNCTION__, msg.string());
1999 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002000 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002001 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002002 String8 msg = String8::format("Unknown device version %x for device %s",
2003 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002004 ALOGE("%s: %s", __FUNCTION__, msg.string());
2005 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2006 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002007 }
2008
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002009 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002010}
2011
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002012Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2013 /*out*/ bool *isSupported) {
2014 ATRACE_CALL();
2015
2016 const String8 id = String8(cameraId);
2017
2018 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2019 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2020
2021 return Status::ok();
2022}
2023
Ruben Brunkcc776712015-02-17 20:18:47 -08002024void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002025 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002026 for (auto& i : mActiveClientManager.getAll()) {
2027 auto clientSp = i->getValue();
2028 if (clientSp.get() == client) {
2029 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002030 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002031 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002032 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002033}
2034
Ruben Brunkcc776712015-02-17 20:18:47 -08002035bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002036 bool ret = false;
2037 {
2038 // Acquire mServiceLock and prevent other clients from connecting
2039 std::unique_ptr<AutoConditionLock> lock =
2040 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002041
Igor Murashkin634a5152013-02-20 17:15:11 -08002042
Ruben Brunkcc776712015-02-17 20:18:47 -08002043 std::vector<sp<BasicClient>> evicted;
2044 for (auto& i : mActiveClientManager.getAll()) {
2045 auto clientSp = i->getValue();
2046 if (clientSp.get() == nullptr) {
2047 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2048 mActiveClientManager.remove(i);
2049 continue;
2050 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002051 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002052 mActiveClientManager.remove(i);
2053 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002054
Ruben Brunkcc776712015-02-17 20:18:47 -08002055 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002056 clientSp->notifyError(
2057 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002058 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002059 }
2060 }
2061
Ruben Brunkcc776712015-02-17 20:18:47 -08002062 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2063 // other clients from connecting in mServiceLockWrapper if held
2064 mServiceLock.unlock();
2065
Ruben Brunk36597b22015-03-20 22:15:57 -07002066 // Do not clear caller identity, remote caller should be client proccess
2067
Ruben Brunkcc776712015-02-17 20:18:47 -08002068 for (auto& i : evicted) {
2069 if (i.get() != nullptr) {
2070 i->disconnect();
2071 ret = true;
2072 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002073 }
2074
Ruben Brunkcc776712015-02-17 20:18:47 -08002075 // Reacquire mServiceLock
2076 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002077
Ruben Brunkcc776712015-02-17 20:18:47 -08002078 } // lock is destroyed, allow further connect calls
2079
2080 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002081}
2082
Ruben Brunkcc776712015-02-17 20:18:47 -08002083std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2084 const String8& cameraId) const {
2085 std::shared_ptr<CameraState> state;
2086 {
2087 Mutex::Autolock lock(mCameraStatesLock);
2088 auto iter = mCameraStates.find(cameraId);
2089 if (iter != mCameraStates.end()) {
2090 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002091 }
2092 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002093 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002094}
2095
Ruben Brunkcc776712015-02-17 20:18:47 -08002096sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2097 // Remove from active clients list
2098 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2099 if (clientDescriptorPtr == nullptr) {
2100 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2101 cameraId.string());
2102 return sp<BasicClient>{nullptr};
2103 }
2104
2105 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07002106}
2107
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002108void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002109 // Acquire mServiceLock and prevent other clients from connecting
2110 std::unique_ptr<AutoConditionLock> lock =
2111 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2112
Ruben Brunk6267b532015-04-30 17:44:07 -07002113 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002114 for (size_t i = 0; i < newUserIds.size(); i++) {
2115 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002116 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002117 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002118 return;
2119 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002120 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002121 }
2122
Ruben Brunka8ca9152015-04-07 14:23:40 -07002123
Ruben Brunk6267b532015-04-30 17:44:07 -07002124 if (newAllowedUsers == mAllowedUsers) {
2125 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2126 return;
2127 }
2128
2129 logUserSwitch(mAllowedUsers, newAllowedUsers);
2130
2131 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002132
2133 // Current user has switched, evict all current clients.
2134 std::vector<sp<BasicClient>> evicted;
2135 for (auto& i : mActiveClientManager.getAll()) {
2136 auto clientSp = i->getValue();
2137
2138 if (clientSp.get() == nullptr) {
2139 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2140 continue;
2141 }
2142
Ruben Brunk6267b532015-04-30 17:44:07 -07002143 // Don't evict clients that are still allowed.
2144 uid_t clientUid = clientSp->getClientUid();
2145 userid_t clientUserId = multiuser_get_user_id(clientUid);
2146 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2147 continue;
2148 }
2149
Ruben Brunk36597b22015-03-20 22:15:57 -07002150 evicted.push_back(clientSp);
2151
2152 String8 curTime = getFormattedCurrentTime();
2153
2154 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2155 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002156
Ruben Brunk36597b22015-03-20 22:15:57 -07002157 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002158 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002159 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2160 " to user switch.", i->getKey().string(),
2161 String8{clientSp->getPackageName()}.string(),
2162 i->getOwnerId(), i->getPriority().getScore(),
2163 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002164
2165 }
2166
2167 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2168 // blocking other clients from connecting in mServiceLockWrapper if held.
2169 mServiceLock.unlock();
2170
2171 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002172 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002173
2174 for (auto& i : evicted) {
2175 i->disconnect();
2176 }
2177
Jayant Chowdhary12361932018-08-27 14:46:13 -07002178 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002179
2180 // Reacquire mServiceLock
2181 mServiceLock.lock();
2182}
Ruben Brunkcc776712015-02-17 20:18:47 -08002183
Ruben Brunka8ca9152015-04-07 14:23:40 -07002184void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002185 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002186 Mutex::Autolock l(mLogLock);
2187 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002188}
2189
Ruben Brunka8ca9152015-04-07 14:23:40 -07002190void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002191 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002192 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002193 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002194 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002195}
2196
2197void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002198 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002199 // Log the clients evicted
2200 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002201 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002202}
2203
2204void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002205 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002206 // Log the client rejected
2207 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002208 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002209}
2210
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002211void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
2212 // Log torch event
2213 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
2214 torchState, clientPid));
2215}
2216
Ruben Brunk6267b532015-04-30 17:44:07 -07002217void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
2218 const std::set<userid_t>& newUserIds) {
2219 String8 newUsers = toString(newUserIds);
2220 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002221 if (oldUsers.size() == 0) {
2222 oldUsers = "<None>";
2223 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07002224 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002225 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07002226 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002227}
2228
2229void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
2230 // Log the device removal
2231 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
2232}
2233
2234void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
2235 // Log the device removal
2236 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
2237}
2238
2239void CameraService::logClientDied(int clientPid, const char* reason) {
2240 // Log the device removal
2241 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07002242}
2243
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002244void CameraService::logServiceError(const char* msg, int errorCode) {
2245 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002246 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002247}
2248
Ruben Brunk36597b22015-03-20 22:15:57 -07002249status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
2250 uint32_t flags) {
2251
Mathias Agopian65ab4712010-07-14 17:59:35 -07002252 // Permission checks
2253 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002254 case SHELL_COMMAND_TRANSACTION: {
2255 int in = data.readFileDescriptor();
2256 int out = data.readFileDescriptor();
2257 int err = data.readFileDescriptor();
2258 int argc = data.readInt32();
2259 Vector<String16> args;
2260 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
2261 args.add(data.readString16());
2262 }
2263 sp<IBinder> unusedCallback;
2264 sp<IResultReceiver> resultReceiver;
2265 status_t status;
2266 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
2267 return status;
2268 }
2269 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
2270 return status;
2271 }
2272 status = shellCommand(in, out, err, args);
2273 if (resultReceiver != nullptr) {
2274 resultReceiver->send(status);
2275 }
2276 return NO_ERROR;
2277 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002278 }
2279
2280 return BnCameraService::onTransact(code, data, reply, flags);
2281}
2282
Mathias Agopian65ab4712010-07-14 17:59:35 -07002283// We share the media players for shutter and recording sound for all clients.
2284// A reference count is kept to determine when we will actually release the
2285// media players.
2286
Jaekyun Seokef498052018-03-23 13:09:44 +09002287sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
2288 sp<MediaPlayer> mp = new MediaPlayer();
2289 status_t error;
2290 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08002291 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09002292 error = mp->prepare();
2293 }
2294 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002295 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09002296 mp->disconnect();
2297 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002298 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002299 }
2300 return mp;
2301}
2302
username5755fea2018-12-27 09:48:08 +08002303void CameraService::increaseSoundRef() {
2304 Mutex::Autolock lock(mSoundLock);
2305 mSoundRef++;
2306}
2307
2308void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002309 ATRACE_CALL();
2310
username5755fea2018-12-27 09:48:08 +08002311 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
2312 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
2313 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
2314 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
2315 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2316 }
2317 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
2318 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
2319 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
2320 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002321 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08002322 }
2323 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
2324 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
2325 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
2326 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2327 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002328 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002329}
2330
username5755fea2018-12-27 09:48:08 +08002331void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002332 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002333 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002334 if (--mSoundRef) return;
2335
2336 for (int i = 0; i < NUM_SOUNDS; i++) {
2337 if (mSoundPlayer[i] != 0) {
2338 mSoundPlayer[i]->disconnect();
2339 mSoundPlayer[i].clear();
2340 }
2341 }
2342}
2343
2344void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002345 ATRACE_CALL();
2346
Mathias Agopian65ab4712010-07-14 17:59:35 -07002347 LOG1("playSound(%d)", kind);
2348 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002349 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002350 sp<MediaPlayer> player = mSoundPlayer[kind];
2351 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08002352 player->seekTo(0);
2353 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002354 }
2355}
2356
2357// ----------------------------------------------------------------------------
2358
2359CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002360 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002361 const String16& clientPackageName,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002362 const String8& cameraIdStr,
2363 int api1CameraId, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002364 int clientPid, uid_t clientUid,
2365 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002366 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08002367 IInterface::asBinder(cameraClient),
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002368 clientPackageName,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002369 cameraIdStr, cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002370 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002371 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002372 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08002373{
Jayant Chowdhary12361932018-08-27 14:46:13 -07002374 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002375 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002376
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002377 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002378
username5755fea2018-12-27 09:48:08 +08002379 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002380
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002381 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002382}
2383
Mathias Agopian65ab4712010-07-14 17:59:35 -07002384// tear down the client
2385CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002386 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08002387 mDestructionStarted = true;
2388
username5755fea2018-12-27 09:48:08 +08002389 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002390 // unconditionally disconnect. function is idempotent
2391 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002392}
2393
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002394sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
2395
Igor Murashkin634a5152013-02-20 17:15:11 -08002396CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002397 const sp<IBinder>& remoteCallback,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002398 const String16& clientPackageName,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002399 const String8& cameraIdStr, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002400 int clientPid, uid_t clientUid,
2401 int servicePid):
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002402 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing),
2403 mClientPackageName(clientPackageName), mClientPid(clientPid), mClientUid(clientUid),
2404 mServicePid(servicePid),
2405 mDisconnected(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002406 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002407 mRemoteBinder(remoteCallback)
Igor Murashkin634a5152013-02-20 17:15:11 -08002408{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002409 if (sCameraService == nullptr) {
2410 sCameraService = cameraService;
2411 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002412 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08002413 mDestructionStarted = false;
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08002414
2415 // In some cases the calling code has no access to the package it runs under.
2416 // For example, NDK camera API.
2417 // In this case we will get the packages for the calling UID and pick the first one
2418 // for attributing the app op. This will work correctly for runtime permissions
2419 // as for legacy apps we will toggle the app op for all packages in the UID.
2420 // The caveat is that the operation may be attributed to the wrong package and
2421 // stats based on app ops may be slightly off.
2422 if (mClientPackageName.size() <= 0) {
2423 sp<IServiceManager> sm = defaultServiceManager();
2424 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2425 if (binder == 0) {
2426 ALOGE("Cannot get permission service");
2427 // Leave mClientPackageName unchanged (empty) and the further interaction
2428 // with camera will fail in BasicClient::startCameraOps
2429 return;
2430 }
2431
2432 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2433 Vector<String16> packages;
2434
2435 permCtrl->getPackagesForUid(mClientUid, packages);
2436
2437 if (packages.isEmpty()) {
2438 ALOGE("No packages for calling UID");
2439 // Leave mClientPackageName unchanged (empty) and the further interaction
2440 // with camera will fail in BasicClient::startCameraOps
2441 return;
2442 }
2443 mClientPackageName = packages[0];
2444 }
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002445 if (!hardware::IPCThreadState::self()->isServingCall()) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002446 mAppOpsManager = std::make_unique<AppOpsManager>();
2447 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002448}
2449
2450CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002451 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08002452 mDestructionStarted = true;
2453}
2454
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002455binder::Status CameraService::BasicClient::disconnect() {
2456 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002457 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002458 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07002459 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002460 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002461
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002462 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002463 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07002464 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
2465 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002466
2467 sp<IBinder> remote = getRemote();
2468 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002469 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08002470 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002471
2472 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07002473 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002474 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
2475 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
2476 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002477
Igor Murashkincba2c162013-03-20 15:56:31 -07002478 // client shouldn't be able to call into us anymore
2479 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002480
2481 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08002482}
2483
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002484status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2485 // No dumping of clients directly over Binder,
2486 // must go through CameraService::dump
2487 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002488 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002489 return OK;
2490}
2491
Ruben Brunkcc776712015-02-17 20:18:47 -08002492String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002493 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08002494}
2495
2496
2497int CameraService::BasicClient::getClientPid() const {
2498 return mClientPid;
2499}
2500
Ruben Brunk6267b532015-04-30 17:44:07 -07002501uid_t CameraService::BasicClient::getClientUid() const {
2502 return mClientUid;
2503}
2504
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002505bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2506 // Defaults to API2.
2507 return level == API_2;
2508}
2509
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002510status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002511 {
2512 Mutex::Autolock l(mAudioRestrictionLock);
2513 mAudioRestriction = mode;
2514 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002515 sCameraService->updateAudioRestriction();
2516 return OK;
2517}
2518
2519int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002520 return sCameraService->updateAudioRestriction();
2521}
2522
2523int32_t CameraService::BasicClient::getAudioRestriction() const {
2524 Mutex::Autolock l(mAudioRestrictionLock);
2525 return mAudioRestriction;
2526}
2527
2528bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
2529 switch (mode) {
2530 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
2531 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
2532 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
2533 return true;
2534 default:
2535 return false;
2536 }
2537}
2538
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002539status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002540 ATRACE_CALL();
2541
Igor Murashkine6800ce2013-03-04 17:25:57 -08002542 {
2543 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002544 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002545 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002546 if (mAppOpsManager != nullptr) {
2547 // Notify app ops that the camera is not available
2548 mOpsCallback = new OpsCallback(this);
2549 int32_t res;
2550 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
2551 mClientPackageName, mOpsCallback);
2552 res = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA,
2553 mClientUid, mClientPackageName, /*startIfModeDefault*/ false);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002554
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002555 if (res == AppOpsManager::MODE_ERRORED) {
2556 ALOGI("Camera %s: Access for \"%s\" has been revoked",
2557 mCameraIdStr.string(), String8(mClientPackageName).string());
2558 return PERMISSION_DENIED;
2559 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002560
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002561 if (res == AppOpsManager::MODE_IGNORED) {
2562 ALOGI("Camera %s: Access for \"%s\" has been restricted",
2563 mCameraIdStr.string(), String8(mClientPackageName).string());
2564 // Return the same error as for device policy manager rejection
2565 return -EACCES;
2566 }
Svetoslav28e8ef72015-05-11 19:21:31 -07002567 }
2568
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002569 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002570
2571 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002572 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002573
Emilian Peev573291c2018-02-10 02:10:56 +00002574 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2575 if (canCastToApiClient(API_2)) {
2576 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2577 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002578 // Transition device state to OPEN
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002579 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
Emilian Peev573291c2018-02-10 02:10:56 +00002580 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002581
Emilian Peev53722fa2019-02-22 17:47:20 -08002582 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
2583
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002584 return OK;
2585}
2586
2587status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002588 ATRACE_CALL();
2589
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002590 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002591 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002592 // Notify app ops that the camera is available again
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002593 if (mAppOpsManager != nullptr) {
2594 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
2595 mClientPackageName);
2596 mOpsActive = false;
2597 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002598 // This function is called when a client disconnects. This should
2599 // release the camera, but actually only if it was in a proper
2600 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002601 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002602 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002603
Ruben Brunkcc776712015-02-17 20:18:47 -08002604 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002605 sCameraService->updateStatus(StatusInternal::PRESENT,
2606 mCameraIdStr, rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002607
Emilian Peev573291c2018-02-10 02:10:56 +00002608 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2609 if (canCastToApiClient(API_2)) {
2610 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2611 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002612 // Transition device state to CLOSED
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002613 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
Emilian Peev573291c2018-02-10 02:10:56 +00002614 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002615 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002616 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002617 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
2618 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002619 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002620 mOpsCallback.clear();
2621
Emilian Peev53722fa2019-02-22 17:47:20 -08002622 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
2623
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002624 return OK;
2625}
2626
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002627void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002628 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002629 if (mAppOpsManager == nullptr) {
2630 return;
2631 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002632 if (op != AppOpsManager::OP_CAMERA) {
2633 ALOGW("Unexpected app ops notification received: %d", op);
2634 return;
2635 }
2636
2637 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002638 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002639 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002640 ALOGV("checkOp returns: %d, %s ", res,
2641 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
2642 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
2643 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
2644 "UNKNOWN");
2645
2646 if (res != AppOpsManager::MODE_ALLOWED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002647 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002648 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08002649 block();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002650 }
2651}
2652
Svet Ganova453d0d2018-01-11 15:37:58 -08002653void CameraService::BasicClient::block() {
2654 ATRACE_CALL();
2655
2656 // Reset the client PID to allow server-initiated disconnect,
2657 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07002658 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08002659 CaptureResultExtras resultExtras; // a dummy result (invalid)
2660 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
2661 disconnect();
2662}
2663
Mathias Agopian65ab4712010-07-14 17:59:35 -07002664// ----------------------------------------------------------------------------
2665
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002666void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07002667 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002668 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07002669 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07002670 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
2671 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
2672 api1ErrorCode = CAMERA_ERROR_DISABLED;
2673 }
2674 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07002675 } else {
2676 ALOGE("mRemoteCallback is NULL!!");
2677 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002678}
2679
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002680// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002681binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002682 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002683 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08002684}
2685
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002686bool CameraService::Client::canCastToApiClient(apiLevel level) const {
2687 return level == API_1;
2688}
2689
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002690CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
2691 mClient(client) {
2692}
2693
2694void CameraService::Client::OpsCallback::opChanged(int32_t op,
2695 const String16& packageName) {
2696 sp<BasicClient> client = mClient.promote();
2697 if (client != NULL) {
2698 client->opChanged(op, packageName);
2699 }
2700}
2701
Mathias Agopian65ab4712010-07-14 17:59:35 -07002702// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08002703// UidPolicy
2704// ----------------------------------------------------------------------------
2705
2706void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002707 Mutex::Autolock _l(mUidLock);
2708
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002709 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07002710 status_t res = mAm.linkToDeath(this);
2711 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08002712 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08002713 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08002714 ActivityManager::PROCESS_STATE_UNKNOWN,
2715 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002716 if (res == OK) {
2717 mRegistered = true;
2718 ALOGV("UidPolicy: Registered with ActivityManager");
2719 }
Svet Ganova453d0d2018-01-11 15:37:58 -08002720}
2721
2722void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002723 Mutex::Autolock _l(mUidLock);
2724
Steven Moreland2f348142019-07-02 15:59:07 -07002725 mAm.unregisterUidObserver(this);
2726 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002727 mRegistered = false;
2728 mActiveUids.clear();
2729 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08002730}
2731
2732void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
2733 onUidIdle(uid, disabled);
2734}
2735
2736void CameraService::UidPolicy::onUidActive(uid_t uid) {
2737 Mutex::Autolock _l(mUidLock);
2738 mActiveUids.insert(uid);
2739}
2740
2741void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
2742 bool deleted = false;
2743 {
2744 Mutex::Autolock _l(mUidLock);
2745 if (mActiveUids.erase(uid) > 0) {
2746 deleted = true;
2747 }
2748 }
2749 if (deleted) {
2750 sp<CameraService> service = mService.promote();
2751 if (service != nullptr) {
2752 service->blockClientsForUid(uid);
2753 }
2754 }
2755}
2756
Emilian Peev53722fa2019-02-22 17:47:20 -08002757void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
2758 int64_t /*procStateSeq*/) {
2759 bool procStateChange = false;
2760 {
2761 Mutex::Autolock _l(mUidLock);
2762 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
2763 (mMonitoredUids[uid].first != procState)) {
2764 mMonitoredUids[uid].first = procState;
2765 procStateChange = true;
2766 }
2767 }
2768
2769 if (procStateChange) {
2770 sp<CameraService> service = mService.promote();
2771 if (service != nullptr) {
2772 service->notifyMonitoredUids();
2773 }
2774 }
2775}
2776
2777void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
2778 Mutex::Autolock _l(mUidLock);
2779 auto it = mMonitoredUids.find(uid);
2780 if (it != mMonitoredUids.end()) {
2781 it->second.second++;
2782 } else {
2783 mMonitoredUids.emplace(
2784 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
2785 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
2786 }
2787}
2788
2789void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
2790 Mutex::Autolock _l(mUidLock);
2791 auto it = mMonitoredUids.find(uid);
2792 if (it != mMonitoredUids.end()) {
2793 it->second.second--;
2794 if (it->second.second == 0) {
2795 mMonitoredUids.erase(it);
2796 }
2797 } else {
2798 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
2799 }
2800}
2801
Svet Ganov7b4ab782018-03-25 12:48:10 -07002802bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002803 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07002804 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08002805}
2806
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07002807static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
2808static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07002809
Svet Ganov7b4ab782018-03-25 12:48:10 -07002810bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002811 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002812 // If activity manager is unreachable, assume everything is active
2813 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002814 return true;
2815 }
2816 auto it = mOverrideUids.find(uid);
2817 if (it != mOverrideUids.end()) {
2818 return it->second;
2819 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07002820 bool active = mActiveUids.find(uid) != mActiveUids.end();
2821 if (!active) {
2822 // We want active UIDs to always access camera with their first attempt since
2823 // there is no guarantee the app is robustly written and would retry getting
2824 // the camera on failure. The inverse case is not a problem as we would take
2825 // camera away soon once we get the callback that the uid is no longer active.
2826 ActivityManager am;
2827 // Okay to access with a lock held as UID changes are dispatched without
2828 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07002829 int64_t startTimeMillis = 0;
2830 do {
2831 // TODO: Fix this b/109950150!
2832 // Okay this is a hack. There is a race between the UID turning active and
2833 // activity being resumed. The proper fix is very risky, so we temporary add
2834 // some polling which should happen pretty rarely anyway as the race is hard
2835 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07002836 active = mActiveUids.find(uid) != mActiveUids.end();
2837 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07002838 if (active) {
2839 break;
2840 }
2841 if (startTimeMillis <= 0) {
2842 startTimeMillis = uptimeMillis();
2843 }
2844 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07002845 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07002846 if (remainingTimeMillis <= 0) {
2847 break;
2848 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07002849 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
2850
2851 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07002852 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07002853 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07002854 } while (true);
2855
Svet Ganov7b4ab782018-03-25 12:48:10 -07002856 if (active) {
2857 // Now that we found out the UID is actually active, cache that
2858 mActiveUids.insert(uid);
2859 }
2860 }
2861 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08002862}
2863
Varun Shahb42f1eb2019-04-16 14:45:13 -07002864int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
2865 Mutex::Autolock _l(mUidLock);
2866 return getProcStateLocked(uid);
2867}
2868
2869int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
2870 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
2871 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
2872 procState = mMonitoredUids[uid].first;
2873 }
2874 return procState;
2875}
2876
Svet Ganov7b4ab782018-03-25 12:48:10 -07002877void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
2878 String16 callingPackage, bool active) {
2879 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08002880}
2881
Svet Ganov7b4ab782018-03-25 12:48:10 -07002882void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
2883 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08002884}
2885
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002886void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
2887 Mutex::Autolock _l(mUidLock);
2888 ALOGV("UidPolicy: ActivityManager has died");
2889 mRegistered = false;
2890 mActiveUids.clear();
2891}
2892
Svet Ganov7b4ab782018-03-25 12:48:10 -07002893void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
2894 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002895 bool wasActive = false;
2896 bool isActive = false;
2897 {
2898 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07002899 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08002900 mOverrideUids.erase(uid);
2901 if (insert) {
2902 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
2903 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07002904 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08002905 }
2906 if (wasActive != isActive && !isActive) {
2907 sp<CameraService> service = mService.promote();
2908 if (service != nullptr) {
2909 service->blockClientsForUid(uid);
2910 }
2911 }
2912}
2913
2914// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08002915// SensorPrivacyPolicy
2916// ----------------------------------------------------------------------------
2917void CameraService::SensorPrivacyPolicy::registerSelf() {
2918 Mutex::Autolock _l(mSensorPrivacyLock);
2919 if (mRegistered) {
2920 return;
2921 }
2922 SensorPrivacyManager spm;
2923 spm.addSensorPrivacyListener(this);
2924 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
2925 status_t res = spm.linkToDeath(this);
2926 if (res == OK) {
2927 mRegistered = true;
2928 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
2929 }
2930}
2931
2932void CameraService::SensorPrivacyPolicy::unregisterSelf() {
2933 Mutex::Autolock _l(mSensorPrivacyLock);
2934 SensorPrivacyManager spm;
2935 spm.removeSensorPrivacyListener(this);
2936 spm.unlinkToDeath(this);
2937 mRegistered = false;
2938 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
2939}
2940
2941bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
2942 Mutex::Autolock _l(mSensorPrivacyLock);
2943 return mSensorPrivacyEnabled;
2944}
2945
2946binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
2947 {
2948 Mutex::Autolock _l(mSensorPrivacyLock);
2949 mSensorPrivacyEnabled = enabled;
2950 }
2951 // if sensor privacy is enabled then block all clients from accessing the camera
2952 if (enabled) {
2953 sp<CameraService> service = mService.promote();
2954 if (service != nullptr) {
2955 service->blockAllClients();
2956 }
2957 }
2958 return binder::Status::ok();
2959}
2960
2961void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
2962 Mutex::Autolock _l(mSensorPrivacyLock);
2963 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
2964 mRegistered = false;
2965}
2966
2967// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08002968// CameraState
2969// ----------------------------------------------------------------------------
2970
2971CameraService::CameraState::CameraState(const String8& id, int cost,
2972 const std::set<String8>& conflicting) : mId(id),
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002973 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08002974
2975CameraService::CameraState::~CameraState() {}
2976
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002977CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08002978 Mutex::Autolock lock(mStatusLock);
2979 return mStatus;
2980}
2981
2982CameraParameters CameraService::CameraState::getShimParams() const {
2983 return mShimParams;
2984}
2985
2986void CameraService::CameraState::setShimParams(const CameraParameters& params) {
2987 mShimParams = params;
2988}
2989
2990int CameraService::CameraState::getCost() const {
2991 return mCost;
2992}
2993
2994std::set<String8> CameraService::CameraState::getConflicting() const {
2995 return mConflicting;
2996}
2997
2998String8 CameraService::CameraState::getId() const {
2999 return mId;
3000}
3001
3002// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07003003// ClientEventListener
3004// ----------------------------------------------------------------------------
3005
3006void CameraService::ClientEventListener::onClientAdded(
3007 const resource_policy::ClientDescriptor<String8,
3008 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003009 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003010 if (basicClient.get() != nullptr) {
3011 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3012 notifier.noteStartCamera(descriptor.getKey(),
3013 static_cast<int>(basicClient->getClientUid()));
3014 }
3015}
3016
3017void CameraService::ClientEventListener::onClientRemoved(
3018 const resource_policy::ClientDescriptor<String8,
3019 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003020 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003021 if (basicClient.get() != nullptr) {
3022 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3023 notifier.noteStopCamera(descriptor.getKey(),
3024 static_cast<int>(basicClient->getClientUid()));
3025 }
3026}
3027
3028
3029// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003030// CameraClientManager
3031// ----------------------------------------------------------------------------
3032
Ruben Brunk99e69712015-05-26 17:25:07 -07003033CameraService::CameraClientManager::CameraClientManager() {
3034 setListener(std::make_shared<ClientEventListener>());
3035}
3036
Ruben Brunkcc776712015-02-17 20:18:47 -08003037CameraService::CameraClientManager::~CameraClientManager() {}
3038
3039sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
3040 const String8& id) const {
3041 auto descriptor = get(id);
3042 if (descriptor == nullptr) {
3043 return sp<BasicClient>{nullptr};
3044 }
3045 return descriptor->getValue();
3046}
3047
3048String8 CameraService::CameraClientManager::toString() const {
3049 auto all = getAll();
3050 String8 ret("[");
3051 bool hasAny = false;
3052 for (auto& i : all) {
3053 hasAny = true;
3054 String8 key = i->getKey();
3055 int32_t cost = i->getCost();
3056 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00003057 int32_t score = i->getPriority().getScore();
3058 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08003059 auto conflicting = i->getConflicting();
3060 auto clientSp = i->getValue();
3061 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07003062 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08003063 if (clientSp.get() != nullptr) {
3064 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07003065 uid_t clientUid = clientSp->getClientUid();
3066 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003067 }
Emilian Peev8131a262017-02-01 12:33:43 +00003068 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
3069 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08003070
Ruben Brunk6267b532015-04-30 17:44:07 -07003071 if (clientSp.get() != nullptr) {
3072 ret.appendFormat("User Id: %d, ", clientUserId);
3073 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003074 if (packageName.size() != 0) {
3075 ret.appendFormat("Client Package Name: %s", packageName.string());
3076 }
3077
3078 ret.append(", Conflicting Client Devices: {");
3079 for (auto& j : conflicting) {
3080 ret.appendFormat("%s, ", j.string());
3081 }
3082 ret.append("})");
3083 }
3084 if (hasAny) ret.append("\n");
3085 ret.append("]\n");
3086 return ret;
3087}
3088
3089CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3090 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00003091 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
3092 int32_t state) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003093
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003094 bool isVendorClient = hardware::IPCThreadState::self()->isServingCall();
3095 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
3096 int32_t state_adj = isVendorClient ? kVendorClientState: state;
3097
Ruben Brunkcc776712015-02-17 20:18:47 -08003098 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003099 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08003100}
3101
3102CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3103 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
3104 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00003105 partial->getConflicting(), partial->getPriority().getScore(),
3106 partial->getOwnerId(), partial->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08003107}
3108
3109// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07003110
3111static const int kDumpLockRetries = 50;
3112static const int kDumpLockSleep = 60000;
3113
3114static bool tryLock(Mutex& mutex)
3115{
3116 bool locked = false;
3117 for (int i = 0; i < kDumpLockRetries; ++i) {
3118 if (mutex.tryLock() == NO_ERROR) {
3119 locked = true;
3120 break;
3121 }
3122 usleep(kDumpLockSleep);
3123 }
3124 return locked;
3125}
3126
3127status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003128 ATRACE_CALL();
3129
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003130 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003131 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003132 CameraThreadState::getCallingPid(),
3133 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003134 return NO_ERROR;
3135 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003136 bool locked = tryLock(mServiceLock);
3137 // failed to lock - CameraService is probably deadlocked
3138 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003139 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003140 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003141
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003142 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003143 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07003144
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003145 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003146 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08003147
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003148 if (locked) mServiceLock.unlock();
3149 return NO_ERROR;
3150 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003151 dprintf(fd, "\n== Service global info: ==\n\n");
3152 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003153 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
3154 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
3155 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
3156 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003157 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003158 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
3159 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003160
3161 dumpEventLog(fd);
3162
3163 bool stateLocked = tryLock(mCameraStatesLock);
3164 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003165 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003166 }
3167
Emilian Peevbd8c5032018-02-14 23:05:40 +00003168 int argSize = args.size();
3169 for (int i = 0; i < argSize; i++) {
3170 if (args[i] == TagMonitor::kMonitorOption) {
3171 if (i + 1 < argSize) {
3172 mMonitorTags = String8(args[i + 1]);
3173 }
3174 break;
3175 }
3176 }
3177
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003178 for (auto& state : mCameraStates) {
3179 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003180
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003181 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003182
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003183 CameraParameters p = state.second->getShimParams();
3184 if (!p.isEmpty()) {
3185 dprintf(fd, " Camera1 API shim is using parameters:\n ");
3186 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003187 }
3188
3189 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08003190 if (clientDescriptor != nullptr) {
3191 dprintf(fd, " Device %s is open. Client instance dump:\n",
3192 cameraId.string());
3193 dprintf(fd, " Client priority score: %d state: %d\n",
3194 clientDescriptor->getPriority().getScore(),
3195 clientDescriptor->getPriority().getState());
3196 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
3197
3198 auto client = clientDescriptor->getValue();
3199 dprintf(fd, " Client package: %s\n",
3200 String8(client->getPackageName()).string());
3201
3202 client->dumpClient(fd, args);
3203 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003204 dprintf(fd, " Device %s is closed, no client instance\n",
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003205 cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003206 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003207
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003208 }
3209
3210 if (stateLocked) mCameraStatesLock.unlock();
3211
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003212 if (locked) mServiceLock.unlock();
3213
Emilian Peevf53f66e2017-04-11 14:29:43 +01003214 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003215
3216 dprintf(fd, "\n== Vendor tags: ==\n\n");
3217
3218 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
3219 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00003220 sp<VendorTagDescriptorCache> cache =
3221 VendorTagDescriptorCache::getGlobalVendorTagCache();
3222 if (cache == NULL) {
3223 dprintf(fd, "No vendor tags.\n");
3224 } else {
3225 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
3226 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003227 } else {
3228 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
3229 }
3230
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003231 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003232 dprintf(fd, "\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003233 camera3::CameraTraces::dump(fd, args);
3234
3235 // Process dump arguments, if any
3236 int n = args.size();
3237 String16 verboseOption("-v");
3238 String16 unreachableOption("--unreachable");
3239 for (int i = 0; i < n; i++) {
3240 if (args[i] == verboseOption) {
3241 // change logging level
3242 if (i + 1 >= n) continue;
3243 String8 levelStr(args[i+1]);
3244 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003245 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003246 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003247 } else if (args[i] == unreachableOption) {
3248 // Dump memory analysis
3249 // TODO - should limit be an argument parameter?
3250 UnreachableMemoryInfo info;
3251 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
3252 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003253 dprintf(fd, "\n== Unable to dump unreachable memory. "
3254 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003255 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003256 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003257 std::string s = info.ToString(/*log_contents*/ true);
3258 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003259 }
3260 }
3261 }
3262 return NO_ERROR;
3263}
3264
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003265void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003266 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003267
3268 Mutex::Autolock l(mLogLock);
3269 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003270 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003271 }
3272
3273 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003274 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003275 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003276 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003277 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003278 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003279}
3280
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003281void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003282 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003283 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
3284 if (mTorchClientMap[i] == who) {
3285 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003286 String8 cameraId = mTorchClientMap.keyAt(i);
3287 status_t res = mFlashlight->setTorchMode(cameraId, false);
3288 if (res) {
3289 ALOGE("%s: torch client died but couldn't turn off torch: "
3290 "%s (%d)", __FUNCTION__, strerror(-res), res);
3291 return;
3292 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003293 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003294 break;
3295 }
3296 }
3297}
3298
Ruben Brunkcc776712015-02-17 20:18:47 -08003299/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003300
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003301 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07003302 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
3303 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003304 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003305 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003306 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003307
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003308 // check torch client
3309 handleTorchClientBinderDied(who);
3310
3311 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08003312 if(!evictClientIdByRemote(who)) {
3313 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003314 return;
3315 }
3316
Ruben Brunkcc776712015-02-17 20:18:47 -08003317 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
3318 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003319}
3320
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003321void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003322 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08003323}
3324
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003325void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
3326 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003327 // Do not lock mServiceLock here or can get into a deadlock from
3328 // connect() -> disconnect -> updateStatus
3329
3330 auto state = getCameraState(cameraId);
3331
3332 if (state == nullptr) {
3333 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
3334 cameraId.string());
3335 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07003336 }
3337
Ruben Brunkcc776712015-02-17 20:18:47 -08003338 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
3339 // of the listeners with both the mStatusStatus and mStatusListenerLock held
3340 state->updateStatus(status, cameraId, rejectSourceStates, [this]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003341 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003342
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003343 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003344 // Update torch status if it has a flash unit.
3345 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003346 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003347 if (getTorchStatusLocked(cameraId, &torchStatus) !=
3348 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003349 TorchModeStatus newTorchStatus =
3350 status == StatusInternal::PRESENT ?
3351 TorchModeStatus::AVAILABLE_OFF :
3352 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003353 if (torchStatus != newTorchStatus) {
3354 onTorchStatusChangedLocked(cameraId, newTorchStatus);
3355 }
3356 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003357 }
3358
3359 Mutex::Autolock lock(mStatusListenerLock);
3360
3361 for (auto& listener : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003362 if (shouldSkipStatusUpdates(cameraId, listener->isVendorListener(),
3363 listener->getListenerPid(), listener->getListenerUid())) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003364 ALOGV("Skipping camera discovery callback for system-only camera %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003365 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003366 continue;
3367 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003368 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08003369 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08003370 }
3371 });
Igor Murashkincba2c162013-03-20 15:56:31 -07003372}
3373
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003374template<class Func>
3375void CameraService::CameraState::updateStatus(StatusInternal status,
3376 const String8& cameraId,
3377 std::initializer_list<StatusInternal> rejectSourceStates,
3378 Func onStatusUpdatedLocked) {
3379 Mutex::Autolock lock(mStatusLock);
3380 StatusInternal oldStatus = mStatus;
3381 mStatus = status;
3382
3383 if (oldStatus == status) {
3384 return;
3385 }
3386
3387 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
3388 cameraId.string(), oldStatus, status);
3389
3390 if (oldStatus == StatusInternal::NOT_PRESENT &&
3391 (status != StatusInternal::PRESENT &&
3392 status != StatusInternal::ENUMERATING)) {
3393
3394 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
3395 __FUNCTION__);
3396 mStatus = oldStatus;
3397 return;
3398 }
3399
3400 /**
3401 * Sometimes we want to conditionally do a transition.
3402 * For example if a client disconnects, we want to go to PRESENT
3403 * only if we weren't already in NOT_PRESENT or ENUMERATING.
3404 */
3405 for (auto& rejectStatus : rejectSourceStates) {
3406 if (oldStatus == rejectStatus) {
3407 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
3408 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
3409 mStatus = oldStatus;
3410 return;
3411 }
3412 }
3413
3414 onStatusUpdatedLocked(cameraId, status);
3415}
3416
Eino-Ville Talvalae8c96c72017-06-27 12:24:07 -07003417void CameraService::updateProxyDeviceState(int newState,
Emilian Peev573291c2018-02-10 02:10:56 +00003418 const String8& cameraId, int facing, const String16& clientName, int apiLevel) {
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003419 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
3420 if (proxyBinder == nullptr) return;
3421 String16 id(cameraId);
Emilian Peev573291c2018-02-10 02:10:56 +00003422 proxyBinder->notifyCameraState(id, newState, facing, clientName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003423}
3424
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003425status_t CameraService::getTorchStatusLocked(
3426 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003427 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003428 if (!status) {
3429 return BAD_VALUE;
3430 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003431 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3432 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003433 // invalid camera ID or the camera doesn't have a flash unit
3434 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003435 }
3436
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003437 *status = mTorchStatusMap.valueAt(index);
3438 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003439}
3440
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003441status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003442 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003443 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3444 if (index == NAME_NOT_FOUND) {
3445 return BAD_VALUE;
3446 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003447 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003448
3449 return OK;
3450}
3451
Svet Ganova453d0d2018-01-11 15:37:58 -08003452void CameraService::blockClientsForUid(uid_t uid) {
3453 const auto clients = mActiveClientManager.getAll();
3454 for (auto& current : clients) {
3455 if (current != nullptr) {
3456 const auto basicClient = current->getValue();
3457 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
3458 basicClient->block();
3459 }
3460 }
3461 }
3462}
3463
Michael Grooverd1d435a2018-12-18 17:39:42 -08003464void CameraService::blockAllClients() {
3465 const auto clients = mActiveClientManager.getAll();
3466 for (auto& current : clients) {
3467 if (current != nullptr) {
3468 const auto basicClient = current->getValue();
3469 if (basicClient.get() != nullptr) {
3470 basicClient->block();
3471 }
3472 }
3473 }
3474}
3475
Svet Ganova453d0d2018-01-11 15:37:58 -08003476// NOTE: This is a remote API - make sure all args are validated
3477status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
3478 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
3479 return PERMISSION_DENIED;
3480 }
3481 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
3482 return BAD_VALUE;
3483 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003484 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003485 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003486 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003487 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003488 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003489 return handleGetUidState(args, out, err);
3490 } else if (args.size() == 1 && args[0] == String16("help")) {
3491 printHelp(out);
3492 return NO_ERROR;
3493 }
3494 printHelp(err);
3495 return BAD_VALUE;
3496}
3497
3498status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003499 String16 packageName = args[1];
3500
Svet Ganova453d0d2018-01-11 15:37:58 -08003501 bool active = false;
3502 if (args[2] == String16("active")) {
3503 active = true;
3504 } else if ((args[2] != String16("idle"))) {
3505 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
3506 return BAD_VALUE;
3507 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003508
3509 int userId = 0;
3510 if (args.size() >= 5 && args[3] == String16("--user")) {
3511 userId = atoi(String8(args[4]));
3512 }
3513
3514 uid_t uid;
3515 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
3516 return BAD_VALUE;
3517 }
3518
3519 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08003520 return NO_ERROR;
3521}
3522
3523status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003524 String16 packageName = args[1];
3525
3526 int userId = 0;
3527 if (args.size() >= 4 && args[2] == String16("--user")) {
3528 userId = atoi(String8(args[3]));
3529 }
3530
3531 uid_t uid;
3532 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003533 return BAD_VALUE;
3534 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003535
3536 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08003537 return NO_ERROR;
3538}
3539
3540status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003541 String16 packageName = args[1];
3542
3543 int userId = 0;
3544 if (args.size() >= 4 && args[2] == String16("--user")) {
3545 userId = atoi(String8(args[3]));
3546 }
3547
3548 uid_t uid;
3549 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003550 return BAD_VALUE;
3551 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003552
3553 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003554 return dprintf(out, "active\n");
3555 } else {
3556 return dprintf(out, "idle\n");
3557 }
3558}
3559
3560status_t CameraService::printHelp(int out) {
3561 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07003562 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
3563 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
3564 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08003565 " help print this message\n");
3566}
3567
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003568int32_t CameraService::updateAudioRestriction() {
3569 Mutex::Autolock lock(mServiceLock);
3570 return updateAudioRestrictionLocked();
3571}
3572
3573int32_t CameraService::updateAudioRestrictionLocked() {
3574 int32_t mode = 0;
3575 // iterate through all active client
3576 for (const auto& i : mActiveClientManager.getAll()) {
3577 const auto clientSp = i->getValue();
3578 mode |= clientSp->getAudioRestriction();
3579 }
3580
3581 bool modeChanged = (mAudioRestriction != mode);
3582 mAudioRestriction = mode;
3583 if (modeChanged) {
3584 mAppOps.setCameraAudioRestriction(mode);
3585 }
3586 return mode;
3587}
3588
Mathias Agopian65ab4712010-07-14 17:59:35 -07003589}; // namespace android