blob: a110c33e42f4dc97377c420d6f137d9eb3cb4c39 [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),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700138 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700139 mSoundRef(0), mInitialized(false),
140 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000141 ALOGI("CameraService started (pid=%d)", getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800142 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700143}
144
Iliyan Malchev8951a972011-04-14 16:55:59 -0700145void CameraService::onFirstRef()
146{
Ruben Brunkcc776712015-02-17 20:18:47 -0800147 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800148
Iliyan Malchev8951a972011-04-14 16:55:59 -0700149 BnCameraService::onFirstRef();
150
Ruben Brunk99e69712015-05-26 17:25:07 -0700151 // Update battery life tracking if service is restarting
152 BatteryNotifier& notifier(BatteryNotifier::getInstance());
153 notifier.noteResetCamera();
154 notifier.noteResetFlashlight();
155
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800156 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800157
Emilian Peevf53f66e2017-04-11 14:29:43 +0100158 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800159 if (res == OK) {
160 mInitialized = true;
161 }
162
Svet Ganova453d0d2018-01-11 15:37:58 -0800163 mUidPolicy = new UidPolicy(this);
164 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800165 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
166 mSensorPrivacyPolicy->registerSelf();
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700167 mAppOps.setCameraAudioRestriction(mAudioRestriction);
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700168 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
169 if (hcs->registerAsService() != android::OK) {
170 ALOGE("%s: Failed to register default android.frameworks.cameraservice.service@1.0",
171 __FUNCTION__);
172 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700173
174 // This needs to be last call in this function, so that it's as close to
175 // ServiceManager::addService() as possible.
176 CameraService::pingCameraServiceProxy();
177 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800178}
179
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800180status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800181 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100182
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800183 std::vector<std::string> deviceIds;
184 {
185 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800186
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800187 if (nullptr == mCameraProviderManager.get()) {
188 mCameraProviderManager = new CameraProviderManager();
189 res = mCameraProviderManager->initialize(this);
190 if (res != OK) {
191 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
192 __FUNCTION__, strerror(-res), res);
193 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100194 }
195 }
196
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800197
198 // Setup vendor tags before we call get_camera_info the first time
199 // because HAL might need to setup static vendor keys in get_camera_info
200 // TODO: maybe put this into CameraProviderManager::initialize()?
201 mCameraProviderManager->setUpVendorTags();
202
203 if (nullptr == mFlashlight.get()) {
204 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700205 }
206
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800207 res = mFlashlight->findFlashUnits();
208 if (res != OK) {
209 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
210 }
211
212 deviceIds = mCameraProviderManager->getCameraDeviceIds();
213 }
214
215
216 for (auto& cameraId : deviceIds) {
217 String8 id8 = String8(cameraId.c_str());
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800218 if (getCameraState(id8) == nullptr) {
219 onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
220 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800221 }
222
223 return OK;
224}
225
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700226sp<ICameraServiceProxy> CameraService::getCameraServiceProxy() {
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800227#ifndef __BRILLO__
Eino-Ville Talvala7d5569f2019-04-08 13:57:54 -0700228 Mutex::Autolock al(sProxyMutex);
229 if (sCameraServiceProxy == nullptr) {
230 sp<IServiceManager> sm = defaultServiceManager();
231 // Use checkService because cameraserver normally starts before the
232 // system server and the proxy service. So the long timeout that getService
233 // has before giving up is inappropriate.
234 sp<IBinder> binder = sm->checkService(String16("media.camera.proxy"));
235 if (binder != nullptr) {
236 sCameraServiceProxy = interface_cast<ICameraServiceProxy>(binder);
237 }
Ruben Brunk2823ce02015-05-19 17:25:13 -0700238 }
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800239#endif
Eino-Ville Talvala7d5569f2019-04-08 13:57:54 -0700240 return sCameraServiceProxy;
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700241}
242
243void CameraService::pingCameraServiceProxy() {
244 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
245 if (proxyBinder == nullptr) return;
Ruben Brunk2823ce02015-05-19 17:25:13 -0700246 proxyBinder->pingForUserUpdate();
Iliyan Malchev8951a972011-04-14 16:55:59 -0700247}
248
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800249void CameraService::broadcastTorchModeStatus(const String8& cameraId, TorchModeStatus status) {
250 Mutex::Autolock lock(mStatusListenerLock);
251
252 for (auto& i : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700253 i->getListener()->onTorchStatusChanged(mapToInterface(status), String16{cameraId});
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800254 }
255}
256
Mathias Agopian65ab4712010-07-14 17:59:35 -0700257CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800258 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800259 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800260 mSensorPrivacyPolicy->unregisterSelf();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700261}
262
Emilian Peevaee727d2017-05-04 16:35:48 +0100263void CameraService::onNewProviderRegistered() {
264 enumerateProviders();
265}
266
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700267void CameraService::filterAPI1SystemCameraLocked(
268 const std::vector<std::string> &normalDeviceIds) {
269 mNormalDeviceIdsWithoutSystemCamera.clear();
270 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700271 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
272 if (getSystemCameraKind(String8(deviceId.c_str()), &deviceKind) != OK) {
273 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
274 continue;
275 }
276 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700277 // All system camera ids will necessarily come after public camera
278 // device ids as per the HAL interface contract.
279 break;
280 }
281 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
282 }
283 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
284 mNormalDeviceIdsWithoutSystemCamera.size());
285}
286
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700287status_t CameraService::getSystemCameraKind(const String8& cameraId, SystemCameraKind *kind) const {
288 auto state = getCameraState(cameraId);
289 if (state != nullptr) {
290 *kind = state->getSystemCameraKind();
291 return OK;
292 }
293 // Hidden physical camera ids won't have CameraState
294 return mCameraProviderManager->getSystemCameraKind(cameraId.c_str(), kind);
295}
296
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800297void CameraService::updateCameraNumAndIds() {
298 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700299 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
300 // Excludes hidden secure cameras
301 mNumberOfCameras =
302 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
303 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800304 mNormalDeviceIds =
305 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700306 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800307}
308
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100309void CameraService::addStates(const String8 id) {
310 std::string cameraId(id.c_str());
311 hardware::camera::common::V1_0::CameraResourceCost cost;
312 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700313 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100314 if (res != OK) {
315 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
316 return;
317 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700318 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
319 if (res != OK) {
320 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
321 return;
322 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100323 std::set<String8> conflicting;
324 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
325 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
326 }
327
328 {
329 Mutex::Autolock lock(mCameraStatesLock);
330 mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700331 conflicting, deviceKind));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100332 }
333
334 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100335 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100336 mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800337
338 broadcastTorchModeStatus(id, TorchModeStatus::AVAILABLE_OFF);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100339 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800340
341 updateCameraNumAndIds();
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100342 logDeviceAdded(id, "Device added");
343}
344
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100345void CameraService::removeStates(const String8 id) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800346 updateCameraNumAndIds();
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100347 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100348 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100349 mTorchStatusMap.removeItem(id);
350 }
351
352 {
353 Mutex::Autolock lock(mCameraStatesLock);
354 mCameraStates.erase(id);
355 }
356}
357
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800358void CameraService::onDeviceStatusChanged(const String8& id,
359 CameraDeviceStatus newHalStatus) {
360 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
361 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700362
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800363 StatusInternal newStatus = mapToInternal(newHalStatus);
364
Ruben Brunkcc776712015-02-17 20:18:47 -0800365 std::shared_ptr<CameraState> state = getCameraState(id);
366
367 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700368 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100369 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700370 __FUNCTION__, id.string());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100371
372 // First add as absent to make sure clients are notified below
373 addStates(id);
374
375 updateStatus(newStatus, id);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700376 } else {
377 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
378 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700379 return;
380 }
381
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800382 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800383
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800384 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800385 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700386 return;
387 }
388
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800389 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700390 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
391 newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800392
393 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
394 // to this device until the status changes
395 updateStatus(StatusInternal::NOT_PRESENT, id);
396
Ruben Brunkcc776712015-02-17 20:18:47 -0800397 sp<BasicClient> clientToDisconnect;
Igor Murashkincba2c162013-03-20 15:56:31 -0700398 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800399 // Don't do this in updateStatus to avoid deadlock over mServiceLock
400 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700401
Ruben Brunkcc776712015-02-17 20:18:47 -0800402 // Remove cached shim parameters
403 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700404
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700405 // Remove the client from the list of active clients, if there is one
Ruben Brunkcc776712015-02-17 20:18:47 -0800406 clientToDisconnect = removeClientLocked(id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700407 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800408
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700409 // Disconnect client
410 if (clientToDisconnect.get() != nullptr) {
411 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
412 __FUNCTION__, id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800413 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800414 clientToDisconnect->notifyError(
415 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -0800416 CaptureResultExtras{});
Ruben Brunkcc776712015-02-17 20:18:47 -0800417 // Ensure not in binder RPC so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -0700418 LOG_ALWAYS_FATAL_IF(CameraThreadState::getCallingPid() != getpid(),
Ruben Brunkcc776712015-02-17 20:18:47 -0800419 "onDeviceStatusChanged must be called from the camera service process!");
420 clientToDisconnect->disconnect();
Igor Murashkincba2c162013-03-20 15:56:31 -0700421 }
422
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100423 removeStates(id);
Ruben Brunkcc776712015-02-17 20:18:47 -0800424 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800425 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700426 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
427 newStatus));
428 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800429 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700430 }
431
Igor Murashkincba2c162013-03-20 15:56:31 -0700432}
433
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800434void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800435 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800436 Mutex::Autolock al(mTorchStatusMutex);
437 onTorchStatusChangedLocked(cameraId, newStatus);
438}
439
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800440void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800441 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800442 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
443 __FUNCTION__, cameraId.string(), newStatus);
444
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800445 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800446 status_t res = getTorchStatusLocked(cameraId, &status);
447 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700448 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
449 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800450 return;
451 }
452 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800453 return;
454 }
455
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800456 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800457 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800458 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
459 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800460 return;
461 }
462
Ruben Brunkcc776712015-02-17 20:18:47 -0800463 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700464 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700465 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700466 auto iter = mTorchUidMap.find(cameraId);
467 if (iter != mTorchUidMap.end()) {
468 int oldUid = iter->second.second;
469 int newUid = iter->second.first;
470 BatteryNotifier& notifier(BatteryNotifier::getInstance());
471 if (oldUid != newUid) {
472 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800473 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700474 notifier.noteFlashlightOff(cameraId, oldUid);
475 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800476 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700477 notifier.noteFlashlightOn(cameraId, newUid);
478 }
479 iter->second.second = newUid;
480 } else {
481 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800482 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700483 notifier.noteFlashlightOn(cameraId, oldUid);
484 } else {
485 notifier.noteFlashlightOff(cameraId, oldUid);
486 }
487 }
488 }
489 }
490
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800491 broadcastTorchModeStatus(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800492}
493
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700494static bool hasPermissionsForSystemCamera(int callingPid, int callingUid) {
495 return checkPermission(sSystemCameraPermission, callingPid, callingUid) &&
496 checkPermission(sCameraPermission, callingPid, callingUid);
497}
498
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800499Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700500 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100501 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700502 bool hasSystemCameraPermissions =
503 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
504 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700505 switch (type) {
506 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700507 if (hasSystemCameraPermissions) {
508 *numCameras = static_cast<int>(mNormalDeviceIds.size());
509 } else {
510 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
511 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800512 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700513 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700514 if (hasSystemCameraPermissions) {
515 *numCameras = mNumberOfCameras;
516 } else {
517 *numCameras = mNumberOfCamerasWithoutSystemCamera;
518 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800519 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700520 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800521 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700522 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800523 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
524 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700525 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800526 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700527}
528
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800529Status CameraService::getCameraInfo(int cameraId,
530 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700531 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100532 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700533 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
534 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
535 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
536 "characteristics for system only device %s: ", cameraIdStr.c_str());
537 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100538
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800539 if (!mInitialized) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800540 return STATUS_ERROR(ERROR_DISCONNECTED,
541 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700542 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700543 bool hasSystemCameraPermissions =
544 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
545 CameraThreadState::getCallingUid());
546 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
547 if (hasSystemCameraPermissions) {
548 cameraIdBound = mNumberOfCameras;
549 }
550 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800551 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
552 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700553 }
554
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800555 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800556 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700557 cameraIdStr.c_str(), cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100558 if (err != OK) {
559 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
560 "Error retrieving camera info from device %d: %s (%d)", cameraId,
561 strerror(-err), err);
Ruben Brunkcc776712015-02-17 20:18:47 -0800562 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100563
Ruben Brunkcc776712015-02-17 20:18:47 -0800564 return ret;
565}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700566
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800567std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700568 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
569 auto callingPid = CameraThreadState::getCallingPid();
570 auto callingUid = CameraThreadState::getCallingUid();
571 if (checkPermission(sSystemCameraPermission, callingPid, callingUid) ||
572 getpid() == callingPid) {
573 deviceIds = &mNormalDeviceIds;
574 }
575 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800576 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700577 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800578 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800579 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800580
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700581 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800582}
583
584String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
585 Mutex::Autolock lock(mServiceLock);
586 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800587}
588
589Status CameraService::getCameraCharacteristics(const String16& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800590 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700591 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700592 if (!cameraInfo) {
593 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800594 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700595 }
596
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800597 if (!mInitialized) {
598 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800599 return STATUS_ERROR(ERROR_DISCONNECTED,
600 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700601 }
602
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700603 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
604 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
605 "characteristics for system only device %s: ", String8(cameraId).string());
606 }
607
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800608 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800609
Emilian Peevf53f66e2017-04-11 14:29:43 +0100610 status_t res = mCameraProviderManager->getCameraCharacteristics(
611 String8(cameraId).string(), cameraInfo);
612 if (res != OK) {
613 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
614 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
615 strerror(-res), res);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700616 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700617 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
618 if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
619 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
620 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
621 "for device %s", String8(cameraId).string());
622 }
Jayant Chowdhary12361932018-08-27 14:46:13 -0700623 int callingPid = CameraThreadState::getCallingPid();
624 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100625 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700626 // If it's not calling from cameraserver, check the permission only if
627 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
628 // it would've already been checked in shouldRejectSystemCameraConnection.
Emilian Peeve20c6372018-08-14 18:45:53 +0100629 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700630 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700631 !checkPermission(sCameraPermission, callingPid, callingUid)) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100632 res = cameraInfo->removePermissionEntries(
633 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
634 &tagsRemoved);
635 if (res != OK) {
636 cameraInfo->clear();
637 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
638 " characteristics needing camera permission for device %s: %s (%d)",
639 String8(cameraId).string(), strerror(-res), res);
640 }
641 }
642
643 if (!tagsRemoved.empty()) {
644 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
645 tagsRemoved.data(), tagsRemoved.size());
646 if (res != OK) {
647 cameraInfo->clear();
648 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
649 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
650 strerror(-res), res);
651 }
652 }
653
Zhijun He2b59be82013-09-25 10:14:30 -0700654 return ret;
655}
656
Ruben Brunkcc776712015-02-17 20:18:47 -0800657String8 CameraService::getFormattedCurrentTime() {
658 time_t now = time(nullptr);
659 char formattedTime[64];
660 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
661 return String8(formattedTime);
662}
663
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800664Status CameraService::getCameraVendorTagDescriptor(
665 /*out*/
666 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700667 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800668 if (!mInitialized) {
669 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800670 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800671 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800672 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
673 if (globalDescriptor != nullptr) {
674 *desc = *(globalDescriptor.get());
675 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800676 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800677}
678
Emilian Peev71c73a22017-03-21 16:35:51 +0000679Status CameraService::getCameraVendorTagCache(
680 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
681 ATRACE_CALL();
682 if (!mInitialized) {
683 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
684 return STATUS_ERROR(ERROR_DISCONNECTED,
685 "Camera subsystem not available");
686 }
687 sp<VendorTagDescriptorCache> globalCache =
688 VendorTagDescriptorCache::getGlobalVendorTagCache();
689 if (globalCache != nullptr) {
690 *cache = *(globalCache.get());
691 }
692 return Status::ok();
693}
694
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800695int CameraService::getDeviceVersion(const String8& cameraId, int* facing) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700696 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800697
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800698 int deviceVersion = 0;
699
Emilian Peevf53f66e2017-04-11 14:29:43 +0100700 status_t res;
701 hardware::hidl_version maxVersion{0,0};
702 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
703 &maxVersion);
704 if (res != OK) return -1;
705 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800706
Emilian Peevf53f66e2017-04-11 14:29:43 +0100707 hardware::CameraInfo info;
708 if (facing) {
709 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800710 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100711 *facing = info.facing;
Igor Murashkin634a5152013-02-20 17:15:11 -0800712 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100713
Igor Murashkin634a5152013-02-20 17:15:11 -0800714 return deviceVersion;
715}
716
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800717Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700718 switch(err) {
719 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800720 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800721 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800722 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
723 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800724 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800725 return STATUS_ERROR(ERROR_DISCONNECTED,
726 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700727 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800728 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
729 "Camera HAL encountered error %d: %s",
730 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700731 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800732}
733
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800734Status CameraService::makeClient(const sp<CameraService>& cameraService,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800735 const sp<IInterface>& cameraCb, const String16& packageName,
736 const std::unique_ptr<String16>& featureId, const String8& cameraId, int api1CameraId,
737 int facing, int clientPid, uid_t clientUid, int servicePid, int halVersion,
738 int deviceVersion, apiLevel effectiveApiLevel,
Ruben Brunkcc776712015-02-17 20:18:47 -0800739 /*out*/sp<BasicClient>* client) {
740
Ruben Brunkcc776712015-02-17 20:18:47 -0800741 if (halVersion < 0 || halVersion == deviceVersion) {
742 // Default path: HAL version is unspecified by caller, create CameraClient
743 // based on device version reported by the HAL.
744 switch(deviceVersion) {
745 case CAMERA_DEVICE_API_VERSION_1_0:
746 if (effectiveApiLevel == API_1) { // Camera1 API route
747 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800748 *client = new CameraClient(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800749 api1CameraId, facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700750 getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800751 } else { // Camera2 API route
752 ALOGW("Camera using old HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800753 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800754 "Camera device \"%s\" HAL version %d does not support camera2 API",
755 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800756 }
757 break;
Ruben Brunkcc776712015-02-17 20:18:47 -0800758 case CAMERA_DEVICE_API_VERSION_3_0:
759 case CAMERA_DEVICE_API_VERSION_3_1:
760 case CAMERA_DEVICE_API_VERSION_3_2:
761 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -0700762 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -0700763 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -0800764 case CAMERA_DEVICE_API_VERSION_3_6:
Ruben Brunkcc776712015-02-17 20:18:47 -0800765 if (effectiveApiLevel == API_1) { // Camera1 API route
766 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800767 *client = new Camera2Client(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800768 cameraId, api1CameraId,
769 facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700770 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800771 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800772 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
773 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800774 *client = new CameraDeviceClient(cameraService, tmp, packageName, featureId,
775 cameraId, facing, clientPid, clientUid, servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800776 }
777 break;
778 default:
779 // Should not be reachable
780 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800781 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800782 "Camera device \"%s\" has unknown HAL version %d",
783 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800784 }
785 } else {
786 // A particular HAL version is requested by caller. Create CameraClient
787 // based on the requested HAL version.
788 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
789 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
790 // Only support higher HAL version device opened as HAL1.0 device.
791 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800792 *client = new CameraClient(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800793 api1CameraId, facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700794 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800795 } else {
796 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
797 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
798 " opened as HAL %x device", halVersion, deviceVersion,
799 CAMERA_DEVICE_API_VERSION_1_0);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800800 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800801 "Camera device \"%s\" (HAL version %d) cannot be opened as HAL version %d",
802 cameraId.string(), deviceVersion, halVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800803 }
804 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800805 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800806}
807
Ruben Brunk6267b532015-04-30 17:44:07 -0700808String8 CameraService::toString(std::set<userid_t> intSet) {
809 String8 s("");
810 bool first = true;
811 for (userid_t i : intSet) {
812 if (first) {
813 s.appendFormat("%d", i);
814 first = false;
815 } else {
816 s.appendFormat(", %d", i);
817 }
818 }
819 return s;
820}
821
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800822int32_t CameraService::mapToInterface(TorchModeStatus status) {
823 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
824 switch (status) {
825 case TorchModeStatus::NOT_AVAILABLE:
826 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
827 break;
828 case TorchModeStatus::AVAILABLE_OFF:
829 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
830 break;
831 case TorchModeStatus::AVAILABLE_ON:
832 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
833 break;
834 default:
835 ALOGW("Unknown new flash status: %d", status);
836 }
837 return serviceStatus;
838}
839
840CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
841 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
842 switch (status) {
843 case CameraDeviceStatus::NOT_PRESENT:
844 serviceStatus = StatusInternal::NOT_PRESENT;
845 break;
846 case CameraDeviceStatus::PRESENT:
847 serviceStatus = StatusInternal::PRESENT;
848 break;
849 case CameraDeviceStatus::ENUMERATING:
850 serviceStatus = StatusInternal::ENUMERATING;
851 break;
852 default:
853 ALOGW("Unknown new HAL device status: %d", status);
854 }
855 return serviceStatus;
856}
857
858int32_t CameraService::mapToInterface(StatusInternal status) {
859 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
860 switch (status) {
861 case StatusInternal::NOT_PRESENT:
862 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
863 break;
864 case StatusInternal::PRESENT:
865 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
866 break;
867 case StatusInternal::ENUMERATING:
868 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
869 break;
870 case StatusInternal::NOT_AVAILABLE:
871 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
872 break;
873 case StatusInternal::UNKNOWN:
874 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
875 break;
876 default:
877 ALOGW("Unknown new internal device status: %d", status);
878 }
879 return serviceStatus;
880}
881
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800882Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -0700883 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700884
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800885 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -0800886 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800887 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800888 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800889 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800890 sp<ICameraClient>{nullptr}, id, cameraId,
891 static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800892 internalPackageName, std::unique_ptr<String16>(), uid, USE_CALLING_PID,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700893 API_1, /*shimUpdateOnly*/ true, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800894 ).isOk()) {
895 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -0700896 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800897 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700898}
899
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800900Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -0700901 /*out*/
902 CameraParameters* parameters) {
903
904 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
905
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800906 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -0700907
908 if (parameters == NULL) {
909 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800910 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700911 }
912
Ruben Brunkcc776712015-02-17 20:18:47 -0800913 String8 id = String8::format("%d", cameraId);
914
915 // Check if we already have parameters
916 {
917 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700918 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800919 auto cameraState = getCameraState(id);
920 if (cameraState == nullptr) {
921 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800922 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
923 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800924 }
925 CameraParameters p = cameraState->getShimParams();
926 if (!p.isEmpty()) {
927 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800928 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700929 }
930 }
931
Jayant Chowdhary12361932018-08-27 14:46:13 -0700932 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -0800933 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -0700934 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800935 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800936 // Error already logged by callee
937 return ret;
938 }
939
940 // Check for parameters again
941 {
942 // Scope for service lock
943 Mutex::Autolock lock(mServiceLock);
944 auto cameraState = getCameraState(id);
945 if (cameraState == nullptr) {
946 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800947 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
948 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -0700949 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800950 CameraParameters p = cameraState->getShimParams();
951 if (!p.isEmpty()) {
952 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800953 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700954 }
955 }
956
Ruben Brunkcc776712015-02-17 20:18:47 -0800957 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
958 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800959 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700960}
961
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800962// Can camera service trust the caller based on the calling UID?
963static bool isTrustedCallingUid(uid_t uid) {
964 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -0700965 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800966 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -0700967 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800968 return true;
969 default:
970 return false;
971 }
972}
973
Nicholas Sauera3620332019-04-03 14:05:17 -0700974static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
975 PermissionController pc;
976 uid = pc.getPackageUid(packageName, 0);
977 if (uid <= 0) {
978 ALOGE("Unknown package: '%s'", String8(packageName).string());
979 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
980 return BAD_VALUE;
981 }
982
983 if (userId < 0) {
984 ALOGE("Invalid user: %d", userId);
985 dprintf(err, "Invalid user: %d\n", userId);
986 return BAD_VALUE;
987 }
988
989 uid = multiuser_get_uid(userId, uid);
990 return NO_ERROR;
991}
992
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800993Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -0700994 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
995 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -0500996
Alex Deymo9c2a2c22016-08-25 11:59:14 -0700997#ifdef __BRILLO__
998 UNUSED(clientName8);
999 UNUSED(clientUid);
1000 UNUSED(clientPid);
1001 UNUSED(originalClientPid);
1002#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001003 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1004 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001005 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001006 return allowed;
1007 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001008#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001009
Jayant Chowdhary12361932018-08-27 14:46:13 -07001010 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001011
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001012 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001013 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1014 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001015 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1016 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001017 }
1018
Ruben Brunkcc776712015-02-17 20:18:47 -08001019 if (getCameraState(cameraId) == nullptr) {
1020 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1021 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001022 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1023 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001024 }
1025
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001026 status_t err = checkIfDeviceIsUsable(cameraId);
1027 if (err != NO_ERROR) {
1028 switch(err) {
1029 case -ENODEV:
1030 case -EBUSY:
1031 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1032 "No camera device with ID \"%s\" currently available", cameraId.string());
1033 default:
1034 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1035 "Unknown error connecting to ID \"%s\"", cameraId.string());
1036 }
1037 }
1038 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001039}
1040
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001041Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001042 const String8& clientName8, int& clientUid, int& clientPid,
1043 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001044 int callingPid = CameraThreadState::getCallingPid();
1045 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001046
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001047 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001048 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001049 clientUid = callingUid;
1050 } else if (!isTrustedCallingUid(callingUid)) {
1051 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1052 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001053 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1054 "Untrusted caller (calling PID %d, UID %d) trying to "
1055 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1056 callingPid, callingUid, cameraId.string(),
1057 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001058 }
1059
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001060 // Check if we can trust clientPid
1061 if (clientPid == USE_CALLING_PID) {
1062 clientPid = callingPid;
1063 } else if (!isTrustedCallingUid(callingUid)) {
1064 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1065 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001066 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1067 "Untrusted caller (calling PID %d, UID %d) trying to "
1068 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1069 callingPid, callingUid, cameraId.string(),
1070 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001071 }
1072
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001073 if (shouldRejectSystemCameraConnection(cameraId)) {
1074 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1075 cameraId.c_str());
1076 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1077 "available", cameraId.string());
1078 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001079 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1080 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1081 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1082 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1083 "found while trying to query device kind", cameraId.string());
1084
1085 }
1086
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001087 // If it's not calling from cameraserver, check the permission if the
1088 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1089 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001090 if (callingPid != getpid() &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001091 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001092 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001093 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001094 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1095 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1096 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001097 }
1098
Svet Ganova453d0d2018-01-11 15:37:58 -08001099 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001100 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001101 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001102 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1103 clientPid, clientUid);
1104 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001105 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1106 "calling UID %d proc state %" PRId32 ")",
1107 clientName8.string(), clientUid, clientPid, cameraId.string(),
1108 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001109 }
1110
Michael Grooverd1d435a2018-12-18 17:39:42 -08001111 // If sensor privacy is enabled then prevent access to the camera
1112 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1113 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1114 return STATUS_ERROR_FMT(ERROR_DISABLED,
1115 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1116 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1117 }
1118
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001119 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1120 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001121 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001122 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001123
Ruben Brunk6267b532015-04-30 17:44:07 -07001124 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001125
Ruben Brunka8ca9152015-04-07 14:23:40 -07001126 // Only allow clients who are being used by the current foreground device user, unless calling
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001127 // from our own process OR the caller is using the cameraserver's HIDL interface.
1128 if (!hardware::IPCThreadState::self()->isServingCall() && callingPid != getpid() &&
1129 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001130 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1131 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1132 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001133 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1134 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1135 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001136 }
1137
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001138 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001139}
1140
1141status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1142 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001143 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001144 if (cameraState == nullptr) {
1145 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1146 cameraId.string());
1147 return -ENODEV;
1148 }
1149
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001150 StatusInternal currentStatus = cameraState->getStatus();
1151 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001152 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1153 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001154 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001155 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001156 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1157 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001158 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001159 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001160
Ruben Brunkcc776712015-02-17 20:18:47 -08001161 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001162}
1163
Ruben Brunkcc776712015-02-17 20:18:47 -08001164void CameraService::finishConnectLocked(const sp<BasicClient>& client,
1165 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001166
Ruben Brunkcc776712015-02-17 20:18:47 -08001167 // Make a descriptor for the incoming client
1168 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
1169 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1170
1171 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1172 String8(client->getPackageName()));
1173
1174 if (evicted.size() > 0) {
1175 // This should never happen - clients should already have been removed in disconnect
1176 for (auto& i : evicted) {
1177 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1178 __FUNCTION__, i->getKey().string());
1179 }
1180
1181 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1182 __FUNCTION__);
1183 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001184
1185 // And register a death notification for the client callback. Do
1186 // this last to avoid Binder policy where a nested Binder
1187 // transaction might be pre-empted to service the client death
1188 // notification if the client process dies before linkToDeath is
1189 // invoked.
1190 sp<IBinder> remoteCallback = client->getRemote();
1191 if (remoteCallback != nullptr) {
1192 remoteCallback->linkToDeath(this);
1193 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001194}
1195
1196status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1197 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
1198 /*out*/
1199 sp<BasicClient>* client,
1200 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001201 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001202 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001203 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001204 DescriptorPtr clientDescriptor;
1205 {
1206 if (effectiveApiLevel == API_1) {
1207 // If we are using API1, any existing client for this camera ID with the same remote
1208 // should be returned rather than evicted to allow MediaRecorder to work properly.
1209
1210 auto current = mActiveClientManager.get(cameraId);
1211 if (current != nullptr) {
1212 auto clientSp = current->getValue();
1213 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001214 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1215 ALOGW("CameraService connect called from same client, but with a different"
1216 " API level, evicting prior client...");
1217 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001218 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001219 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001220 *client = clientSp;
1221 return NO_ERROR;
1222 }
1223 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001224 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001225 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001226
Ruben Brunkcc776712015-02-17 20:18:47 -08001227 // Get current active client PIDs
1228 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1229 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001230
Emilian Peev8131a262017-02-01 12:33:43 +00001231 std::vector<int> priorityScores(ownerPids.size());
1232 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001233
Emilian Peev8131a262017-02-01 12:33:43 +00001234 // Get priority scores of all active PIDs
1235 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1236 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1237 /*out*/&priorityScores[0]);
1238 if (err != OK) {
1239 ALOGE("%s: Priority score query failed: %d",
1240 __FUNCTION__, err);
1241 return err;
1242 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001243
Ruben Brunkcc776712015-02-17 20:18:47 -08001244 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001245 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001246 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001247 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001248 resource_policy::ClientPriority(priorityScores[i], states[i],
1249 /* isVendorClient won't get copied over*/ false));
Ruben Brunkcc776712015-02-17 20:18:47 -08001250 }
1251 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001252
Ruben Brunkcc776712015-02-17 20:18:47 -08001253 // Get state for the given cameraId
1254 auto state = getCameraState(cameraId);
1255 if (state == nullptr) {
1256 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1257 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001258 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001259 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001260 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001261
1262 // Make descriptor for incoming client
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001263 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001264 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1265 state->getConflicting(),
Emilian Peev8131a262017-02-01 12:33:43 +00001266 priorityScores[priorityScores.size() - 1],
1267 clientPid,
1268 states[states.size() - 1]);
Ruben Brunkcc776712015-02-17 20:18:47 -08001269
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001270 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1271
Ruben Brunkcc776712015-02-17 20:18:47 -08001272 // Find clients that would be evicted
1273 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1274
1275 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1276 // background, so we cannot do evictions
1277 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1278 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1279 " priority).", clientPid);
1280
1281 sp<BasicClient> clientSp = clientDescriptor->getValue();
1282 String8 curTime = getFormattedCurrentTime();
1283 auto incompatibleClients =
1284 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1285
1286 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001287 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001288 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001289 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001290
1291 for (auto& i : incompatibleClients) {
1292 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001293 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1294 i->getKey().string(),
1295 String8{i->getValue()->getPackageName()}.string(),
1296 i->getOwnerId(), i->getPriority().getScore(),
1297 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001298 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001299 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001300 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001301 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001302 }
1303
1304 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001305 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001306 mEventLog.add(msg);
1307
1308 return -EBUSY;
1309 }
1310
1311 for (auto& i : evicted) {
1312 sp<BasicClient> clientSp = i->getValue();
1313 if (clientSp.get() == nullptr) {
1314 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1315
1316 // TODO: Remove this
1317 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1318 __FUNCTION__);
1319 mActiveClientManager.remove(i);
1320 continue;
1321 }
1322
1323 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1324 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001325 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001326
Ruben Brunkcc776712015-02-17 20:18:47 -08001327 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001328 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001329 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1330 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001331 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001332 i->getOwnerId(), i->getPriority().getScore(),
1333 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001334 packageName.string(), clientPid, clientPriority.getScore(),
1335 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001336
1337 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001338 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001339 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001340 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001341 }
1342
Ruben Brunkcc776712015-02-17 20:18:47 -08001343 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1344 // other clients from connecting in mServiceLockWrapper if held
1345 mServiceLock.unlock();
1346
1347 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001348 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001349
1350 // Destroy evicted clients
1351 for (auto& i : evictedClients) {
1352 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001353 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001354 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001355
Jayant Chowdhary12361932018-08-27 14:46:13 -07001356 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001357
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001358 for (const auto& i : evictedClients) {
1359 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1360 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1361 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1362 if (ret == TIMED_OUT) {
1363 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1364 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1365 mActiveClientManager.toString().string());
1366 return -EBUSY;
1367 }
1368 if (ret != NO_ERROR) {
1369 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1370 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1371 ret, mActiveClientManager.toString().string());
1372 return ret;
1373 }
1374 }
1375
1376 evictedClients.clear();
1377
Ruben Brunkcc776712015-02-17 20:18:47 -08001378 // Once clients have been disconnected, relock
1379 mServiceLock.lock();
1380
1381 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1382 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1383 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001384 }
1385
Ruben Brunkcc776712015-02-17 20:18:47 -08001386 *partial = clientDescriptor;
1387 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001388}
1389
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001390Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001391 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001392 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001393 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001394 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001395 int clientPid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001396 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001397 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001398
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001399 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001400 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001401
1402 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001403 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001404 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001405 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, std::unique_ptr<String16>(),
1406 clientUid, clientPid, API_1, /*shimUpdateOnly*/ false, /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001407
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001408 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001409 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001410 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001411 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001412 }
1413
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001414 *device = client;
1415 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001416}
1417
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001418Status CameraService::connectLegacy(
Zhijun Heb10cdad2014-06-16 16:38:35 -07001419 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001420 int api1CameraId, int halVersion,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001421 const String16& clientPackageName,
Zhijun Heb10cdad2014-06-16 16:38:35 -07001422 int clientUid,
1423 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001424 sp<ICamera>* device) {
Zhijun Heb10cdad2014-06-16 16:38:35 -07001425
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001426 ATRACE_CALL();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001427 String8 id = cameraIdIntToStr(api1CameraId);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001428
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001429 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001430 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001431 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId, halVersion,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001432 clientPackageName, std::unique_ptr<String16>(), clientUid, USE_CALLING_PID, API_1,
1433 /*shimUpdateOnly*/ false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001434
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001435 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001436 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001437 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001438 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001439 }
1440
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001441 *device = client;
1442 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001443}
1444
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001445bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1446 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001447 // If the client is not a vendor client, don't add listener if
1448 // a) the camera is a publicly hidden secure camera OR
1449 // b) the camera is a system only camera and the client doesn't
1450 // have android.permission.SYSTEM_CAMERA permissions.
1451 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1452 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1453 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001454 return true;
1455 }
1456 return false;
1457}
1458
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001459bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1460 // Rules for rejection:
1461 // 1) If cameraserver tries to access this camera device, accept the
1462 // connection.
1463 // 2) The camera device is a publicly hidden secure camera device AND some
1464 // component is trying to access it on a non-hwbinder thread (generally a non HAL client),
1465 // reject it.
1466 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1467 // and the serving thread is a non hwbinder thread, the client must have
1468 // android.permission.SYSTEM_CAMERA permissions to connect.
1469
1470 int cPid = CameraThreadState::getCallingPid();
1471 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001472 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1473 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
1474 ALOGE("%s: Invalid camera id %s, ", __FUNCTION__, cameraId.c_str());
1475 return true;
1476 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001477
1478 // (1) Cameraserver trying to connect, accept.
1479 if (CameraThreadState::getCallingPid() == getpid()) {
1480 return false;
1481 }
1482 // (2)
1483 if (!hardware::IPCThreadState::self()->isServingCall() &&
1484 systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
1485 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1486 return true;
1487 }
1488 // (3) Here we only check for permissions if it is a system only camera device. This is since
1489 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1490 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1491 // same behavior for system camera devices.
1492 if (!hardware::IPCThreadState::self()->isServingCall() &&
1493 systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1494 !hasPermissionsForSystemCamera(cPid, cUid)) {
1495 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1496 cameraId.c_str());
1497 return true;
1498 }
1499
1500 return false;
1501}
1502
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001503Status CameraService::connectDevice(
1504 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001505 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001506 const String16& clientPackageName,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001507 const std::unique_ptr<String16>& clientFeatureId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001508 int clientUid,
1509 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001510 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001511
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001512 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001513 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001514 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001515 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001516 String16 clientPackageNameAdj = clientPackageName;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001517
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001518 if (hardware::IPCThreadState::self()->isServingCall()) {
1519 std::string vendorClient =
1520 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1521 clientPackageNameAdj = String16(vendorClient.c_str());
1522 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001523 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001524 /*api1CameraId*/-1,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001525 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageNameAdj, clientFeatureId,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001526 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001527
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001528 if(!ret.isOk()) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001529 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageNameAdj),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001530 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001531 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001532 }
1533
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001534 *device = client;
1535 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001536}
1537
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001538template<class CALLBACK, class CLIENT>
1539Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001540 int api1CameraId, int halVersion, const String16& clientPackageName,
1541 const std::unique_ptr<String16>& clientFeatureId, int clientUid, int clientPid,
1542 apiLevel effectiveApiLevel, bool shimUpdateOnly,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001543 /*out*/sp<CLIENT>& device) {
1544 binder::Status ret = binder::Status::ok();
1545
1546 String8 clientName8(clientPackageName);
1547
1548 int originalClientPid = 0;
1549
1550 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) for HAL version %s and "
1551 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
1552 (halVersion == -1) ? "default" : std::to_string(halVersion).c_str(),
1553 static_cast<int>(effectiveApiLevel));
1554
1555 sp<CLIENT> client = nullptr;
1556 {
1557 // Acquire mServiceLock and prevent other clients from connecting
1558 std::unique_ptr<AutoConditionLock> lock =
1559 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1560
1561 if (lock == nullptr) {
1562 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1563 , clientPid);
1564 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1565 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1566 cameraId.string(), clientName8.string(), clientPid);
1567 }
1568
1569 // Enforce client permissions and do basic sanity checks
1570 if(!(ret = validateConnectLocked(cameraId, clientName8,
1571 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1572 return ret;
1573 }
1574
1575 // Check the shim parameters after acquiring lock, if they have already been updated and
1576 // we were doing a shim update, return immediately
1577 if (shimUpdateOnly) {
1578 auto cameraState = getCameraState(cameraId);
1579 if (cameraState != nullptr) {
1580 if (!cameraState->getShimParams().isEmpty()) return ret;
1581 }
1582 }
1583
1584 status_t err;
1585
1586 sp<BasicClient> clientTmp = nullptr;
1587 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1588 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
1589 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
1590 /*out*/&partial)) != NO_ERROR) {
1591 switch (err) {
1592 case -ENODEV:
1593 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1594 "No camera device with ID \"%s\" currently available",
1595 cameraId.string());
1596 case -EBUSY:
1597 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1598 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1599 cameraId.string());
1600 default:
1601 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1602 "Unexpected error %s (%d) opening camera \"%s\"",
1603 strerror(-err), err, cameraId.string());
1604 }
1605 }
1606
1607 if (clientTmp.get() != nullptr) {
1608 // Handle special case for API1 MediaRecorder where the existing client is returned
1609 device = static_cast<CLIENT*>(clientTmp.get());
1610 return ret;
1611 }
1612
1613 // give flashlight a chance to close devices if necessary.
1614 mFlashlight->prepareDeviceOpen(cameraId);
1615
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001616 int facing = -1;
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001617 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001618 if (facing == -1) {
1619 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1620 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1621 "Unable to get camera device \"%s\" facing", cameraId.string());
1622 }
1623
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001624 sp<BasicClient> tmp = nullptr;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001625 if(!(ret = makeClient(this, cameraCb, clientPackageName, clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001626 cameraId, api1CameraId, facing,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001627 clientPid, clientUid, getpid(),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001628 halVersion, deviceVersion, effectiveApiLevel,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001629 /*out*/&tmp)).isOk()) {
1630 return ret;
1631 }
1632 client = static_cast<CLIENT*>(tmp.get());
1633
1634 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1635 __FUNCTION__);
1636
Emilian Peevbd8c5032018-02-14 23:05:40 +00001637 err = client->initialize(mCameraProviderManager, mMonitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001638 if (err != OK) {
1639 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001640 // Errors could be from the HAL module open call or from AppOpsManager
1641 switch(err) {
1642 case BAD_VALUE:
1643 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1644 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1645 case -EBUSY:
1646 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1647 "Camera \"%s\" is already open", cameraId.string());
1648 case -EUSERS:
1649 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1650 "Too many cameras already open, cannot open camera \"%s\"",
1651 cameraId.string());
1652 case PERMISSION_DENIED:
1653 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1654 "No permission to open camera \"%s\"", cameraId.string());
1655 case -EACCES:
1656 return STATUS_ERROR_FMT(ERROR_DISABLED,
1657 "Camera \"%s\" disabled by policy", cameraId.string());
1658 case -ENODEV:
1659 default:
1660 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1661 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1662 strerror(-err), err);
1663 }
1664 }
1665
1666 // Update shim paremeters for legacy clients
1667 if (effectiveApiLevel == API_1) {
1668 // Assume we have always received a Client subclass for API1
1669 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1670 String8 rawParams = shimClient->getParameters();
1671 CameraParameters params(rawParams);
1672
1673 auto cameraState = getCameraState(cameraId);
1674 if (cameraState != nullptr) {
1675 cameraState->setShimParams(params);
1676 } else {
1677 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1678 __FUNCTION__, cameraId.string());
1679 }
1680 }
1681
1682 if (shimUpdateOnly) {
1683 // If only updating legacy shim parameters, immediately disconnect client
1684 mServiceLock.unlock();
1685 client->disconnect();
1686 mServiceLock.lock();
1687 } else {
1688 // Otherwise, add client to active clients list
1689 finishConnectLocked(client, partial);
1690 }
1691 } // lock is destroyed, allow further connect calls
1692
1693 // Important: release the mutex here so the client can call back into the service from its
1694 // destructor (can be at the end of the call)
1695 device = client;
1696 return ret;
1697}
1698
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001699Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001700 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001701 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001702
1703 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001704 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001705 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001706 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1707 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001708 }
1709
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001710 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07001711 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001712
1713 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001714 auto state = getCameraState(id);
1715 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001716 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001717 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1718 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001719 }
1720
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001721 StatusInternal cameraStatus = state->getStatus();
1722 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001723 cameraStatus != StatusInternal::NOT_AVAILABLE) {
1724 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001725 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1726 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001727 }
1728
1729 {
1730 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001731 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001732 status_t err = getTorchStatusLocked(id, &status);
1733 if (err != OK) {
1734 if (err == NAME_NOT_FOUND) {
1735 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1736 "Camera \"%s\" does not have a flash unit", id.string());
1737 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001738 ALOGE("%s: getting current torch status failed for camera %s",
1739 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001740 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1741 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
1742 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001743 }
1744
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001745 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001746 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001747 ALOGE("%s: torch mode of camera %s is not available because "
1748 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001749 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1750 "Torch for camera \"%s\" is not available due to an existing camera user",
1751 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001752 } else {
1753 ALOGE("%s: torch mode of camera %s is not available due to "
1754 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001755 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1756 "Torch for camera \"%s\" is not available due to insufficient resources",
1757 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001758 }
1759 }
1760 }
1761
Ruben Brunk99e69712015-05-26 17:25:07 -07001762 {
1763 // Update UID map - this is used in the torch status changed callbacks, so must be done
1764 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001765 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001766 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1767 mTorchUidMap[id].first = uid;
1768 mTorchUidMap[id].second = uid;
1769 } else {
1770 // Set the pending UID
1771 mTorchUidMap[id].first = uid;
1772 }
1773 }
1774
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001775 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001776
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001777 if (err != OK) {
1778 int32_t errorCode;
1779 String8 msg;
1780 switch (err) {
1781 case -ENOSYS:
1782 msg = String8::format("Camera \"%s\" has no flashlight",
1783 id.string());
1784 errorCode = ERROR_ILLEGAL_ARGUMENT;
1785 break;
1786 default:
1787 msg = String8::format(
1788 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1789 id.string(), enabled, strerror(-err), err);
1790 errorCode = ERROR_INVALID_OPERATION;
1791 }
1792 ALOGE("%s: %s", __FUNCTION__, msg.string());
1793 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001794 }
1795
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001796 {
1797 // update the link to client's death
1798 Mutex::Autolock al(mTorchClientMapMutex);
1799 ssize_t index = mTorchClientMap.indexOfKey(id);
1800 if (enabled) {
1801 if (index == NAME_NOT_FOUND) {
1802 mTorchClientMap.add(id, clientBinder);
1803 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001804 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001805 mTorchClientMap.replaceValueAt(index, clientBinder);
1806 }
1807 clientBinder->linkToDeath(this);
1808 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001809 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001810 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001811 }
1812
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07001813 int clientPid = CameraThreadState::getCallingPid();
1814 const char *id_cstr = id.c_str();
1815 const char *torchState = enabled ? "on" : "off";
1816 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
1817 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001818 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001819}
1820
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001821Status CameraService::notifySystemEvent(int32_t eventId,
1822 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001823 const int pid = CameraThreadState::getCallingPid();
1824 const int selfPid = getpid();
1825
1826 // Permission checks
1827 if (pid != selfPid) {
1828 // Ensure we're being called by system_server, or similar process with
1829 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001830 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001831 const int uid = CameraThreadState::getCallingUid();
1832 ALOGE("Permission Denial: cannot send updates to camera service about system"
1833 " events from pid=%d, uid=%d", pid, uid);
1834 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09001835 "No permission to send updates to camera service about system events"
1836 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001837 }
1838 }
1839
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001840 ATRACE_CALL();
1841
Ruben Brunk36597b22015-03-20 22:15:57 -07001842 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001843 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001844 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07001845 // from a system server crash
1846 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08001847 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001848 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07001849 break;
1850 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001851 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07001852 default: {
1853 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1854 eventId);
1855 break;
1856 }
1857 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001858 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07001859}
1860
Emilian Peev53722fa2019-02-22 17:47:20 -08001861void CameraService::notifyMonitoredUids() {
1862 Mutex::Autolock lock(mStatusListenerLock);
1863
1864 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001865 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08001866 if (!ret.isOk()) {
1867 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
1868 ret.exceptionCode());
1869 }
1870 }
1871}
1872
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08001873Status CameraService::notifyDeviceStateChange(int64_t newState) {
1874 const int pid = CameraThreadState::getCallingPid();
1875 const int selfPid = getpid();
1876
1877 // Permission checks
1878 if (pid != selfPid) {
1879 // Ensure we're being called by system_server, or similar process with
1880 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001881 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08001882 const int uid = CameraThreadState::getCallingUid();
1883 ALOGE("Permission Denial: cannot send updates to camera service about device"
1884 " state changes from pid=%d, uid=%d", pid, uid);
1885 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1886 "No permission to send updates to camera service about device state"
1887 " changes from pid=%d, uid=%d", pid, uid);
1888 }
1889 }
1890
1891 ATRACE_CALL();
1892
1893 using hardware::camera::provider::V2_5::DeviceState;
1894 hardware::hidl_bitfield<DeviceState> newDeviceState{};
1895 if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
1896 newDeviceState |= DeviceState::BACK_COVERED;
1897 }
1898 if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
1899 newDeviceState |= DeviceState::FRONT_COVERED;
1900 }
1901 if (newState & ICameraService::DEVICE_STATE_FOLDED) {
1902 newDeviceState |= DeviceState::FOLDED;
1903 }
1904 // Only map vendor bits directly
1905 uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
1906 newDeviceState |= vendorBits;
1907
1908 ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
1909 Mutex::Autolock l(mServiceLock);
1910 mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
1911
1912 return Status::ok();
1913}
1914
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001915Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
1916 /*out*/
1917 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001918 return addListenerHelper(listener, cameraStatuses);
1919}
1920
1921Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
1922 /*out*/
1923 std::vector<hardware::CameraStatus> *cameraStatuses,
1924 bool isVendorListener) {
1925
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001926 ATRACE_CALL();
1927
Igor Murashkinbfc99152013-02-27 12:55:20 -08001928 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08001929
Ruben Brunk3450ba72015-06-16 11:00:37 -07001930 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001931 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001932 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001933 }
1934
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001935 auto clientUid = CameraThreadState::getCallingUid();
1936 auto clientPid = CameraThreadState::getCallingPid();
1937
Igor Murashkinbfc99152013-02-27 12:55:20 -08001938 Mutex::Autolock lock(mServiceLock);
1939
Ruben Brunkcc776712015-02-17 20:18:47 -08001940 {
1941 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08001942 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001943 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001944 ALOGW("%s: Tried to add listener %p which was already subscribed",
1945 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001946 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08001947 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001948 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001949
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001950 sp<ServiceListener> serviceListener =
1951 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08001952 auto ret = serviceListener->initialize();
1953 if (ret != NO_ERROR) {
1954 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
1955 strerror(-ret), ret);
1956 ALOGE("%s: %s", __FUNCTION__, msg.string());
1957 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
1958 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001959 // The listener still needs to be added to the list of listeners, regardless of what
1960 // permissions the listener process has / whether it is a vendor listener. Since it might be
1961 // eligible to listen to other camera ids.
1962 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08001963 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08001964 }
1965
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001966 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07001967 {
Ruben Brunkcc776712015-02-17 20:18:47 -08001968 Mutex::Autolock lock(mCameraStatesLock);
1969 for (auto& i : mCameraStates) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001970 cameraStatuses->emplace_back(i.first, mapToInterface(i.second->getStatus()));
Igor Murashkincba2c162013-03-20 15:56:31 -07001971 }
1972 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001973 // Remove the camera statuses that should be hidden from the client, we do
1974 // this after collecting the states in order to avoid holding
1975 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
1976 // the same time.
1977 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
1978 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
1979 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1980 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
1981 ALOGE("%s: Invalid camera id %s, skipping status update",
1982 __FUNCTION__, s.cameraId.c_str());
1983 return true;
1984 }
1985 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
1986 clientUid);}), cameraStatuses->end());
1987
Igor Murashkincba2c162013-03-20 15:56:31 -07001988
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001989 /*
1990 * Immediately signal current torch status to this listener only
1991 * This may be a subset of all the devices, so don't include it in the response directly
1992 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001993 {
1994 Mutex::Autolock al(mTorchStatusMutex);
1995 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001996 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001997 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001998 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001999 }
2000
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002001 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002002}
Ruben Brunkcc776712015-02-17 20:18:47 -08002003
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002004Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002005 ATRACE_CALL();
2006
Igor Murashkinbfc99152013-02-27 12:55:20 -08002007 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2008
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002009 if (listener == 0) {
2010 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002011 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002012 }
2013
Igor Murashkinbfc99152013-02-27 12:55:20 -08002014 Mutex::Autolock lock(mServiceLock);
2015
Ruben Brunkcc776712015-02-17 20:18:47 -08002016 {
2017 Mutex::Autolock lock(mStatusListenerLock);
2018 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002019 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2020 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2021 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002022 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002023 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002024 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002025 }
2026 }
2027
2028 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2029 __FUNCTION__, listener.get());
2030
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002031 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002032}
2033
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002034Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002035
2036 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002037 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2038
2039 if (parameters == NULL) {
2040 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002041 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002042 }
2043
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002044 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002045
2046 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002047 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002048 // Error logged by caller
2049 return ret;
2050 }
2051
2052 String8 shimParamsString8 = shimParams.flatten();
2053 String16 shimParamsString16 = String16(shimParamsString8);
2054
2055 *parameters = shimParamsString16;
2056
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002057 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002058}
2059
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002060Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2061 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002062 ATRACE_CALL();
2063
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002064 const String8 id = String8(cameraId);
2065
2066 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002067
2068 switch (apiVersion) {
2069 case API_VERSION_1:
2070 case API_VERSION_2:
2071 break;
2072 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002073 String8 msg = String8::format("Unknown API version %d", apiVersion);
2074 ALOGE("%s: %s", __FUNCTION__, msg.string());
2075 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002076 }
2077
Emilian Peev28ad2ea2017-02-07 16:14:32 +00002078 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002079 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002080 case CAMERA_DEVICE_API_VERSION_1_0:
2081 case CAMERA_DEVICE_API_VERSION_3_0:
2082 case CAMERA_DEVICE_API_VERSION_3_1:
2083 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002084 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2085 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002086 *isSupported = false;
2087 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002088 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2089 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002090 *isSupported = true;
2091 }
2092 break;
2093 case CAMERA_DEVICE_API_VERSION_3_2:
2094 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07002095 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002096 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -08002097 case CAMERA_DEVICE_API_VERSION_3_6:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002098 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2099 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002100 *isSupported = true;
2101 break;
2102 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002103 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002104 ALOGE("%s: %s", __FUNCTION__, msg.string());
2105 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002106 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002107 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002108 String8 msg = String8::format("Unknown device version %x for device %s",
2109 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002110 ALOGE("%s: %s", __FUNCTION__, msg.string());
2111 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2112 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002113 }
2114
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002115 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002116}
2117
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002118Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2119 /*out*/ bool *isSupported) {
2120 ATRACE_CALL();
2121
2122 const String8 id = String8(cameraId);
2123
2124 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2125 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2126
2127 return Status::ok();
2128}
2129
Ruben Brunkcc776712015-02-17 20:18:47 -08002130void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002131 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002132 for (auto& i : mActiveClientManager.getAll()) {
2133 auto clientSp = i->getValue();
2134 if (clientSp.get() == client) {
2135 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002136 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002137 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002138 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002139}
2140
Ruben Brunkcc776712015-02-17 20:18:47 -08002141bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002142 bool ret = false;
2143 {
2144 // Acquire mServiceLock and prevent other clients from connecting
2145 std::unique_ptr<AutoConditionLock> lock =
2146 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002147
Igor Murashkin634a5152013-02-20 17:15:11 -08002148
Ruben Brunkcc776712015-02-17 20:18:47 -08002149 std::vector<sp<BasicClient>> evicted;
2150 for (auto& i : mActiveClientManager.getAll()) {
2151 auto clientSp = i->getValue();
2152 if (clientSp.get() == nullptr) {
2153 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2154 mActiveClientManager.remove(i);
2155 continue;
2156 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002157 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002158 mActiveClientManager.remove(i);
2159 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002160
Ruben Brunkcc776712015-02-17 20:18:47 -08002161 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002162 clientSp->notifyError(
2163 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002164 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002165 }
2166 }
2167
Ruben Brunkcc776712015-02-17 20:18:47 -08002168 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2169 // other clients from connecting in mServiceLockWrapper if held
2170 mServiceLock.unlock();
2171
Ruben Brunk36597b22015-03-20 22:15:57 -07002172 // Do not clear caller identity, remote caller should be client proccess
2173
Ruben Brunkcc776712015-02-17 20:18:47 -08002174 for (auto& i : evicted) {
2175 if (i.get() != nullptr) {
2176 i->disconnect();
2177 ret = true;
2178 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002179 }
2180
Ruben Brunkcc776712015-02-17 20:18:47 -08002181 // Reacquire mServiceLock
2182 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002183
Ruben Brunkcc776712015-02-17 20:18:47 -08002184 } // lock is destroyed, allow further connect calls
2185
2186 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002187}
2188
Ruben Brunkcc776712015-02-17 20:18:47 -08002189std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2190 const String8& cameraId) const {
2191 std::shared_ptr<CameraState> state;
2192 {
2193 Mutex::Autolock lock(mCameraStatesLock);
2194 auto iter = mCameraStates.find(cameraId);
2195 if (iter != mCameraStates.end()) {
2196 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002197 }
2198 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002199 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002200}
2201
Ruben Brunkcc776712015-02-17 20:18:47 -08002202sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2203 // Remove from active clients list
2204 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2205 if (clientDescriptorPtr == nullptr) {
2206 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2207 cameraId.string());
2208 return sp<BasicClient>{nullptr};
2209 }
2210
2211 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07002212}
2213
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002214void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002215 // Acquire mServiceLock and prevent other clients from connecting
2216 std::unique_ptr<AutoConditionLock> lock =
2217 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2218
Ruben Brunk6267b532015-04-30 17:44:07 -07002219 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002220 for (size_t i = 0; i < newUserIds.size(); i++) {
2221 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002222 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002223 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002224 return;
2225 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002226 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002227 }
2228
Ruben Brunka8ca9152015-04-07 14:23:40 -07002229
Ruben Brunk6267b532015-04-30 17:44:07 -07002230 if (newAllowedUsers == mAllowedUsers) {
2231 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2232 return;
2233 }
2234
2235 logUserSwitch(mAllowedUsers, newAllowedUsers);
2236
2237 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002238
2239 // Current user has switched, evict all current clients.
2240 std::vector<sp<BasicClient>> evicted;
2241 for (auto& i : mActiveClientManager.getAll()) {
2242 auto clientSp = i->getValue();
2243
2244 if (clientSp.get() == nullptr) {
2245 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2246 continue;
2247 }
2248
Ruben Brunk6267b532015-04-30 17:44:07 -07002249 // Don't evict clients that are still allowed.
2250 uid_t clientUid = clientSp->getClientUid();
2251 userid_t clientUserId = multiuser_get_user_id(clientUid);
2252 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2253 continue;
2254 }
2255
Ruben Brunk36597b22015-03-20 22:15:57 -07002256 evicted.push_back(clientSp);
2257
2258 String8 curTime = getFormattedCurrentTime();
2259
2260 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2261 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002262
Ruben Brunk36597b22015-03-20 22:15:57 -07002263 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002264 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002265 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2266 " to user switch.", i->getKey().string(),
2267 String8{clientSp->getPackageName()}.string(),
2268 i->getOwnerId(), i->getPriority().getScore(),
2269 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002270
2271 }
2272
2273 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2274 // blocking other clients from connecting in mServiceLockWrapper if held.
2275 mServiceLock.unlock();
2276
2277 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002278 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002279
2280 for (auto& i : evicted) {
2281 i->disconnect();
2282 }
2283
Jayant Chowdhary12361932018-08-27 14:46:13 -07002284 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002285
2286 // Reacquire mServiceLock
2287 mServiceLock.lock();
2288}
Ruben Brunkcc776712015-02-17 20:18:47 -08002289
Ruben Brunka8ca9152015-04-07 14:23:40 -07002290void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002291 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002292 Mutex::Autolock l(mLogLock);
2293 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002294}
2295
Ruben Brunka8ca9152015-04-07 14:23:40 -07002296void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002297 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002298 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002299 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002300 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002301}
2302
2303void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002304 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002305 // Log the clients evicted
2306 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002307 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002308}
2309
2310void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002311 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002312 // Log the client rejected
2313 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002314 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002315}
2316
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002317void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
2318 // Log torch event
2319 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
2320 torchState, clientPid));
2321}
2322
Ruben Brunk6267b532015-04-30 17:44:07 -07002323void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
2324 const std::set<userid_t>& newUserIds) {
2325 String8 newUsers = toString(newUserIds);
2326 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002327 if (oldUsers.size() == 0) {
2328 oldUsers = "<None>";
2329 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07002330 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002331 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07002332 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002333}
2334
2335void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
2336 // Log the device removal
2337 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
2338}
2339
2340void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
2341 // Log the device removal
2342 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
2343}
2344
2345void CameraService::logClientDied(int clientPid, const char* reason) {
2346 // Log the device removal
2347 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07002348}
2349
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002350void CameraService::logServiceError(const char* msg, int errorCode) {
2351 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002352 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002353}
2354
Ruben Brunk36597b22015-03-20 22:15:57 -07002355status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
2356 uint32_t flags) {
2357
Mathias Agopian65ab4712010-07-14 17:59:35 -07002358 // Permission checks
2359 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002360 case SHELL_COMMAND_TRANSACTION: {
2361 int in = data.readFileDescriptor();
2362 int out = data.readFileDescriptor();
2363 int err = data.readFileDescriptor();
2364 int argc = data.readInt32();
2365 Vector<String16> args;
2366 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
2367 args.add(data.readString16());
2368 }
2369 sp<IBinder> unusedCallback;
2370 sp<IResultReceiver> resultReceiver;
2371 status_t status;
2372 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
2373 return status;
2374 }
2375 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
2376 return status;
2377 }
2378 status = shellCommand(in, out, err, args);
2379 if (resultReceiver != nullptr) {
2380 resultReceiver->send(status);
2381 }
2382 return NO_ERROR;
2383 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002384 }
2385
2386 return BnCameraService::onTransact(code, data, reply, flags);
2387}
2388
Mathias Agopian65ab4712010-07-14 17:59:35 -07002389// We share the media players for shutter and recording sound for all clients.
2390// A reference count is kept to determine when we will actually release the
2391// media players.
2392
Jaekyun Seokef498052018-03-23 13:09:44 +09002393sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
2394 sp<MediaPlayer> mp = new MediaPlayer();
2395 status_t error;
2396 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08002397 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09002398 error = mp->prepare();
2399 }
2400 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002401 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09002402 mp->disconnect();
2403 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002404 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002405 }
2406 return mp;
2407}
2408
username5755fea2018-12-27 09:48:08 +08002409void CameraService::increaseSoundRef() {
2410 Mutex::Autolock lock(mSoundLock);
2411 mSoundRef++;
2412}
2413
2414void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002415 ATRACE_CALL();
2416
username5755fea2018-12-27 09:48:08 +08002417 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
2418 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
2419 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
2420 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
2421 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2422 }
2423 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
2424 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
2425 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
2426 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002427 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08002428 }
2429 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
2430 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
2431 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
2432 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2433 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002434 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002435}
2436
username5755fea2018-12-27 09:48:08 +08002437void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002438 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002439 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002440 if (--mSoundRef) return;
2441
2442 for (int i = 0; i < NUM_SOUNDS; i++) {
2443 if (mSoundPlayer[i] != 0) {
2444 mSoundPlayer[i]->disconnect();
2445 mSoundPlayer[i].clear();
2446 }
2447 }
2448}
2449
2450void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002451 ATRACE_CALL();
2452
Mathias Agopian65ab4712010-07-14 17:59:35 -07002453 LOG1("playSound(%d)", kind);
2454 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002455 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002456 sp<MediaPlayer> player = mSoundPlayer[kind];
2457 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08002458 player->seekTo(0);
2459 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002460 }
2461}
2462
2463// ----------------------------------------------------------------------------
2464
2465CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002466 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002467 const String16& clientPackageName,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002468 const std::unique_ptr<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002469 const String8& cameraIdStr,
2470 int api1CameraId, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002471 int clientPid, uid_t clientUid,
2472 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002473 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08002474 IInterface::asBinder(cameraClient),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002475 clientPackageName, clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002476 cameraIdStr, cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002477 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002478 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002479 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08002480{
Jayant Chowdhary12361932018-08-27 14:46:13 -07002481 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002482 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002483
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002484 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002485
username5755fea2018-12-27 09:48:08 +08002486 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002487
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002488 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002489}
2490
Mathias Agopian65ab4712010-07-14 17:59:35 -07002491// tear down the client
2492CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002493 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08002494 mDestructionStarted = true;
2495
username5755fea2018-12-27 09:48:08 +08002496 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002497 // unconditionally disconnect. function is idempotent
2498 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002499}
2500
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002501sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
2502
Igor Murashkin634a5152013-02-20 17:15:11 -08002503CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002504 const sp<IBinder>& remoteCallback,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002505 const String16& clientPackageName, const std::unique_ptr<String16>& clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002506 const String8& cameraIdStr, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002507 int clientPid, uid_t clientUid,
2508 int servicePid):
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002509 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002510 mClientPackageName(clientPackageName),
2511 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002512 mServicePid(servicePid),
2513 mDisconnected(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002514 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002515 mRemoteBinder(remoteCallback)
Igor Murashkin634a5152013-02-20 17:15:11 -08002516{
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002517 if (clientFeatureId) {
2518 mClientFeatureId = std::unique_ptr<String16>(new String16(*clientFeatureId));
2519 } else {
2520 mClientFeatureId = std::unique_ptr<String16>();
2521 }
2522
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002523 if (sCameraService == nullptr) {
2524 sCameraService = cameraService;
2525 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002526 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08002527 mDestructionStarted = false;
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08002528
2529 // In some cases the calling code has no access to the package it runs under.
2530 // For example, NDK camera API.
2531 // In this case we will get the packages for the calling UID and pick the first one
2532 // for attributing the app op. This will work correctly for runtime permissions
2533 // as for legacy apps we will toggle the app op for all packages in the UID.
2534 // The caveat is that the operation may be attributed to the wrong package and
2535 // stats based on app ops may be slightly off.
2536 if (mClientPackageName.size() <= 0) {
2537 sp<IServiceManager> sm = defaultServiceManager();
2538 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2539 if (binder == 0) {
2540 ALOGE("Cannot get permission service");
2541 // Leave mClientPackageName unchanged (empty) and the further interaction
2542 // with camera will fail in BasicClient::startCameraOps
2543 return;
2544 }
2545
2546 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2547 Vector<String16> packages;
2548
2549 permCtrl->getPackagesForUid(mClientUid, packages);
2550
2551 if (packages.isEmpty()) {
2552 ALOGE("No packages for calling UID");
2553 // Leave mClientPackageName unchanged (empty) and the further interaction
2554 // with camera will fail in BasicClient::startCameraOps
2555 return;
2556 }
2557 mClientPackageName = packages[0];
2558 }
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002559 if (!hardware::IPCThreadState::self()->isServingCall()) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002560 mAppOpsManager = std::make_unique<AppOpsManager>();
2561 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002562}
2563
2564CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002565 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08002566 mDestructionStarted = true;
2567}
2568
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002569binder::Status CameraService::BasicClient::disconnect() {
2570 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002571 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002572 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07002573 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002574 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002575
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002576 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002577 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07002578 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
2579 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002580
2581 sp<IBinder> remote = getRemote();
2582 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002583 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08002584 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002585
2586 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07002587 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002588 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
2589 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
2590 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002591
Igor Murashkincba2c162013-03-20 15:56:31 -07002592 // client shouldn't be able to call into us anymore
2593 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002594
2595 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08002596}
2597
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002598status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2599 // No dumping of clients directly over Binder,
2600 // must go through CameraService::dump
2601 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002602 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002603 return OK;
2604}
2605
Ruben Brunkcc776712015-02-17 20:18:47 -08002606String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002607 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08002608}
2609
2610
2611int CameraService::BasicClient::getClientPid() const {
2612 return mClientPid;
2613}
2614
Ruben Brunk6267b532015-04-30 17:44:07 -07002615uid_t CameraService::BasicClient::getClientUid() const {
2616 return mClientUid;
2617}
2618
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002619bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2620 // Defaults to API2.
2621 return level == API_2;
2622}
2623
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002624status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002625 {
2626 Mutex::Autolock l(mAudioRestrictionLock);
2627 mAudioRestriction = mode;
2628 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002629 sCameraService->updateAudioRestriction();
2630 return OK;
2631}
2632
2633int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002634 return sCameraService->updateAudioRestriction();
2635}
2636
2637int32_t CameraService::BasicClient::getAudioRestriction() const {
2638 Mutex::Autolock l(mAudioRestrictionLock);
2639 return mAudioRestriction;
2640}
2641
2642bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
2643 switch (mode) {
2644 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
2645 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
2646 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
2647 return true;
2648 default:
2649 return false;
2650 }
2651}
2652
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002653status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002654 ATRACE_CALL();
2655
Igor Murashkine6800ce2013-03-04 17:25:57 -08002656 {
2657 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002658 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002659 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002660 if (mAppOpsManager != nullptr) {
2661 // Notify app ops that the camera is not available
2662 mOpsCallback = new OpsCallback(this);
2663 int32_t res;
2664 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
2665 mClientPackageName, mOpsCallback);
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002666 res = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
2667 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
2668 String16("start camera ") + String16(mCameraIdStr));
Igor Murashkine6800ce2013-03-04 17:25:57 -08002669
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002670 if (res == AppOpsManager::MODE_ERRORED) {
2671 ALOGI("Camera %s: Access for \"%s\" has been revoked",
2672 mCameraIdStr.string(), String8(mClientPackageName).string());
2673 return PERMISSION_DENIED;
2674 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002675
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002676 if (res == AppOpsManager::MODE_IGNORED) {
2677 ALOGI("Camera %s: Access for \"%s\" has been restricted",
2678 mCameraIdStr.string(), String8(mClientPackageName).string());
2679 // Return the same error as for device policy manager rejection
2680 return -EACCES;
2681 }
Svetoslav28e8ef72015-05-11 19:21:31 -07002682 }
2683
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002684 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002685
2686 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002687 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002688
Emilian Peev573291c2018-02-10 02:10:56 +00002689 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2690 if (canCastToApiClient(API_2)) {
2691 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2692 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002693 // Transition device state to OPEN
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002694 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
Emilian Peev573291c2018-02-10 02:10:56 +00002695 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002696
Emilian Peev53722fa2019-02-22 17:47:20 -08002697 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
2698
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002699 return OK;
2700}
2701
2702status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002703 ATRACE_CALL();
2704
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002705 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002706 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002707 // Notify app ops that the camera is available again
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002708 if (mAppOpsManager != nullptr) {
2709 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002710 mClientPackageName, mClientFeatureId);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002711 mOpsActive = false;
2712 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002713 // This function is called when a client disconnects. This should
2714 // release the camera, but actually only if it was in a proper
2715 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002716 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002717 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002718
Ruben Brunkcc776712015-02-17 20:18:47 -08002719 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002720 sCameraService->updateStatus(StatusInternal::PRESENT,
2721 mCameraIdStr, rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002722
Emilian Peev573291c2018-02-10 02:10:56 +00002723 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2724 if (canCastToApiClient(API_2)) {
2725 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2726 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002727 // Transition device state to CLOSED
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002728 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
Emilian Peev573291c2018-02-10 02:10:56 +00002729 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002730 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002731 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002732 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
2733 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002734 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002735 mOpsCallback.clear();
2736
Emilian Peev53722fa2019-02-22 17:47:20 -08002737 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
2738
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002739 return OK;
2740}
2741
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002742void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002743 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002744 if (mAppOpsManager == nullptr) {
2745 return;
2746 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002747 if (op != AppOpsManager::OP_CAMERA) {
2748 ALOGW("Unexpected app ops notification received: %d", op);
2749 return;
2750 }
2751
2752 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002753 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002754 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002755 ALOGV("checkOp returns: %d, %s ", res,
2756 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
2757 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
2758 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
2759 "UNKNOWN");
2760
2761 if (res != AppOpsManager::MODE_ALLOWED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002762 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002763 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08002764 block();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002765 }
2766}
2767
Svet Ganova453d0d2018-01-11 15:37:58 -08002768void CameraService::BasicClient::block() {
2769 ATRACE_CALL();
2770
2771 // Reset the client PID to allow server-initiated disconnect,
2772 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07002773 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08002774 CaptureResultExtras resultExtras; // a dummy result (invalid)
2775 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
2776 disconnect();
2777}
2778
Mathias Agopian65ab4712010-07-14 17:59:35 -07002779// ----------------------------------------------------------------------------
2780
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002781sp<CameraService> CameraService::OfflineClient::sCameraService;
2782
2783status_t CameraService::OfflineClient::startCameraOps() {
2784 // TODO
2785 return OK;
2786}
2787
2788status_t CameraService::OfflineClient::finishCameraOps() {
2789 // TODO
2790 return OK;
2791}
2792
2793// ----------------------------------------------------------------------------
2794
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002795void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07002796 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002797 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07002798 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07002799 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
2800 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
2801 api1ErrorCode = CAMERA_ERROR_DISABLED;
2802 }
2803 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07002804 } else {
2805 ALOGE("mRemoteCallback is NULL!!");
2806 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002807}
2808
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002809// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002810binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002811 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002812 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08002813}
2814
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002815bool CameraService::Client::canCastToApiClient(apiLevel level) const {
2816 return level == API_1;
2817}
2818
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002819CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
2820 mClient(client) {
2821}
2822
2823void CameraService::Client::OpsCallback::opChanged(int32_t op,
2824 const String16& packageName) {
2825 sp<BasicClient> client = mClient.promote();
2826 if (client != NULL) {
2827 client->opChanged(op, packageName);
2828 }
2829}
2830
Mathias Agopian65ab4712010-07-14 17:59:35 -07002831// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08002832// UidPolicy
2833// ----------------------------------------------------------------------------
2834
2835void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002836 Mutex::Autolock _l(mUidLock);
2837
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002838 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07002839 status_t res = mAm.linkToDeath(this);
2840 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08002841 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08002842 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08002843 ActivityManager::PROCESS_STATE_UNKNOWN,
2844 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002845 if (res == OK) {
2846 mRegistered = true;
2847 ALOGV("UidPolicy: Registered with ActivityManager");
2848 }
Svet Ganova453d0d2018-01-11 15:37:58 -08002849}
2850
2851void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002852 Mutex::Autolock _l(mUidLock);
2853
Steven Moreland2f348142019-07-02 15:59:07 -07002854 mAm.unregisterUidObserver(this);
2855 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002856 mRegistered = false;
2857 mActiveUids.clear();
2858 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08002859}
2860
2861void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
2862 onUidIdle(uid, disabled);
2863}
2864
2865void CameraService::UidPolicy::onUidActive(uid_t uid) {
2866 Mutex::Autolock _l(mUidLock);
2867 mActiveUids.insert(uid);
2868}
2869
2870void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
2871 bool deleted = false;
2872 {
2873 Mutex::Autolock _l(mUidLock);
2874 if (mActiveUids.erase(uid) > 0) {
2875 deleted = true;
2876 }
2877 }
2878 if (deleted) {
2879 sp<CameraService> service = mService.promote();
2880 if (service != nullptr) {
2881 service->blockClientsForUid(uid);
2882 }
2883 }
2884}
2885
Emilian Peev53722fa2019-02-22 17:47:20 -08002886void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07002887 int64_t procStateSeq __unused, int32_t capability __unused) {
Emilian Peev53722fa2019-02-22 17:47:20 -08002888 bool procStateChange = false;
2889 {
2890 Mutex::Autolock _l(mUidLock);
2891 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
2892 (mMonitoredUids[uid].first != procState)) {
2893 mMonitoredUids[uid].first = procState;
2894 procStateChange = true;
2895 }
2896 }
2897
2898 if (procStateChange) {
2899 sp<CameraService> service = mService.promote();
2900 if (service != nullptr) {
2901 service->notifyMonitoredUids();
2902 }
2903 }
2904}
2905
2906void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
2907 Mutex::Autolock _l(mUidLock);
2908 auto it = mMonitoredUids.find(uid);
2909 if (it != mMonitoredUids.end()) {
2910 it->second.second++;
2911 } else {
2912 mMonitoredUids.emplace(
2913 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
2914 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
2915 }
2916}
2917
2918void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
2919 Mutex::Autolock _l(mUidLock);
2920 auto it = mMonitoredUids.find(uid);
2921 if (it != mMonitoredUids.end()) {
2922 it->second.second--;
2923 if (it->second.second == 0) {
2924 mMonitoredUids.erase(it);
2925 }
2926 } else {
2927 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
2928 }
2929}
2930
Svet Ganov7b4ab782018-03-25 12:48:10 -07002931bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002932 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07002933 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08002934}
2935
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07002936static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
2937static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07002938
Svet Ganov7b4ab782018-03-25 12:48:10 -07002939bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002940 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002941 // If activity manager is unreachable, assume everything is active
2942 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002943 return true;
2944 }
2945 auto it = mOverrideUids.find(uid);
2946 if (it != mOverrideUids.end()) {
2947 return it->second;
2948 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07002949 bool active = mActiveUids.find(uid) != mActiveUids.end();
2950 if (!active) {
2951 // We want active UIDs to always access camera with their first attempt since
2952 // there is no guarantee the app is robustly written and would retry getting
2953 // the camera on failure. The inverse case is not a problem as we would take
2954 // camera away soon once we get the callback that the uid is no longer active.
2955 ActivityManager am;
2956 // Okay to access with a lock held as UID changes are dispatched without
2957 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07002958 int64_t startTimeMillis = 0;
2959 do {
2960 // TODO: Fix this b/109950150!
2961 // Okay this is a hack. There is a race between the UID turning active and
2962 // activity being resumed. The proper fix is very risky, so we temporary add
2963 // some polling which should happen pretty rarely anyway as the race is hard
2964 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07002965 active = mActiveUids.find(uid) != mActiveUids.end();
2966 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07002967 if (active) {
2968 break;
2969 }
2970 if (startTimeMillis <= 0) {
2971 startTimeMillis = uptimeMillis();
2972 }
2973 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07002974 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07002975 if (remainingTimeMillis <= 0) {
2976 break;
2977 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07002978 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
2979
2980 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07002981 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07002982 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07002983 } while (true);
2984
Svet Ganov7b4ab782018-03-25 12:48:10 -07002985 if (active) {
2986 // Now that we found out the UID is actually active, cache that
2987 mActiveUids.insert(uid);
2988 }
2989 }
2990 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08002991}
2992
Varun Shahb42f1eb2019-04-16 14:45:13 -07002993int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
2994 Mutex::Autolock _l(mUidLock);
2995 return getProcStateLocked(uid);
2996}
2997
2998int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
2999 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3000 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3001 procState = mMonitoredUids[uid].first;
3002 }
3003 return procState;
3004}
3005
Svet Ganov7b4ab782018-03-25 12:48:10 -07003006void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3007 String16 callingPackage, bool active) {
3008 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003009}
3010
Svet Ganov7b4ab782018-03-25 12:48:10 -07003011void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3012 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003013}
3014
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003015void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3016 Mutex::Autolock _l(mUidLock);
3017 ALOGV("UidPolicy: ActivityManager has died");
3018 mRegistered = false;
3019 mActiveUids.clear();
3020}
3021
Svet Ganov7b4ab782018-03-25 12:48:10 -07003022void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3023 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003024 bool wasActive = false;
3025 bool isActive = false;
3026 {
3027 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003028 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003029 mOverrideUids.erase(uid);
3030 if (insert) {
3031 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3032 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003033 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003034 }
3035 if (wasActive != isActive && !isActive) {
3036 sp<CameraService> service = mService.promote();
3037 if (service != nullptr) {
3038 service->blockClientsForUid(uid);
3039 }
3040 }
3041}
3042
3043// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08003044// SensorPrivacyPolicy
3045// ----------------------------------------------------------------------------
3046void CameraService::SensorPrivacyPolicy::registerSelf() {
3047 Mutex::Autolock _l(mSensorPrivacyLock);
3048 if (mRegistered) {
3049 return;
3050 }
3051 SensorPrivacyManager spm;
3052 spm.addSensorPrivacyListener(this);
3053 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
3054 status_t res = spm.linkToDeath(this);
3055 if (res == OK) {
3056 mRegistered = true;
3057 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3058 }
3059}
3060
3061void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3062 Mutex::Autolock _l(mSensorPrivacyLock);
3063 SensorPrivacyManager spm;
3064 spm.removeSensorPrivacyListener(this);
3065 spm.unlinkToDeath(this);
3066 mRegistered = false;
3067 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3068}
3069
3070bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3071 Mutex::Autolock _l(mSensorPrivacyLock);
3072 return mSensorPrivacyEnabled;
3073}
3074
3075binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3076 {
3077 Mutex::Autolock _l(mSensorPrivacyLock);
3078 mSensorPrivacyEnabled = enabled;
3079 }
3080 // if sensor privacy is enabled then block all clients from accessing the camera
3081 if (enabled) {
3082 sp<CameraService> service = mService.promote();
3083 if (service != nullptr) {
3084 service->blockAllClients();
3085 }
3086 }
3087 return binder::Status::ok();
3088}
3089
3090void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3091 Mutex::Autolock _l(mSensorPrivacyLock);
3092 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3093 mRegistered = false;
3094}
3095
3096// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003097// CameraState
3098// ----------------------------------------------------------------------------
3099
3100CameraService::CameraState::CameraState(const String8& id, int cost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003101 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind) : mId(id),
3102 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
3103 mSystemCameraKind(systemCameraKind) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003104
3105CameraService::CameraState::~CameraState() {}
3106
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003107CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003108 Mutex::Autolock lock(mStatusLock);
3109 return mStatus;
3110}
3111
3112CameraParameters CameraService::CameraState::getShimParams() const {
3113 return mShimParams;
3114}
3115
3116void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3117 mShimParams = params;
3118}
3119
3120int CameraService::CameraState::getCost() const {
3121 return mCost;
3122}
3123
3124std::set<String8> CameraService::CameraState::getConflicting() const {
3125 return mConflicting;
3126}
3127
3128String8 CameraService::CameraState::getId() const {
3129 return mId;
3130}
3131
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003132SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3133 return mSystemCameraKind;
3134}
3135
Ruben Brunkcc776712015-02-17 20:18:47 -08003136// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07003137// ClientEventListener
3138// ----------------------------------------------------------------------------
3139
3140void CameraService::ClientEventListener::onClientAdded(
3141 const resource_policy::ClientDescriptor<String8,
3142 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003143 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003144 if (basicClient.get() != nullptr) {
3145 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3146 notifier.noteStartCamera(descriptor.getKey(),
3147 static_cast<int>(basicClient->getClientUid()));
3148 }
3149}
3150
3151void CameraService::ClientEventListener::onClientRemoved(
3152 const resource_policy::ClientDescriptor<String8,
3153 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003154 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003155 if (basicClient.get() != nullptr) {
3156 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3157 notifier.noteStopCamera(descriptor.getKey(),
3158 static_cast<int>(basicClient->getClientUid()));
3159 }
3160}
3161
3162
3163// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003164// CameraClientManager
3165// ----------------------------------------------------------------------------
3166
Ruben Brunk99e69712015-05-26 17:25:07 -07003167CameraService::CameraClientManager::CameraClientManager() {
3168 setListener(std::make_shared<ClientEventListener>());
3169}
3170
Ruben Brunkcc776712015-02-17 20:18:47 -08003171CameraService::CameraClientManager::~CameraClientManager() {}
3172
3173sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
3174 const String8& id) const {
3175 auto descriptor = get(id);
3176 if (descriptor == nullptr) {
3177 return sp<BasicClient>{nullptr};
3178 }
3179 return descriptor->getValue();
3180}
3181
3182String8 CameraService::CameraClientManager::toString() const {
3183 auto all = getAll();
3184 String8 ret("[");
3185 bool hasAny = false;
3186 for (auto& i : all) {
3187 hasAny = true;
3188 String8 key = i->getKey();
3189 int32_t cost = i->getCost();
3190 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00003191 int32_t score = i->getPriority().getScore();
3192 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08003193 auto conflicting = i->getConflicting();
3194 auto clientSp = i->getValue();
3195 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07003196 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08003197 if (clientSp.get() != nullptr) {
3198 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07003199 uid_t clientUid = clientSp->getClientUid();
3200 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003201 }
Emilian Peev8131a262017-02-01 12:33:43 +00003202 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
3203 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08003204
Ruben Brunk6267b532015-04-30 17:44:07 -07003205 if (clientSp.get() != nullptr) {
3206 ret.appendFormat("User Id: %d, ", clientUserId);
3207 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003208 if (packageName.size() != 0) {
3209 ret.appendFormat("Client Package Name: %s", packageName.string());
3210 }
3211
3212 ret.append(", Conflicting Client Devices: {");
3213 for (auto& j : conflicting) {
3214 ret.appendFormat("%s, ", j.string());
3215 }
3216 ret.append("})");
3217 }
3218 if (hasAny) ret.append("\n");
3219 ret.append("]\n");
3220 return ret;
3221}
3222
3223CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3224 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00003225 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
3226 int32_t state) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003227
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003228 bool isVendorClient = hardware::IPCThreadState::self()->isServingCall();
3229 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
3230 int32_t state_adj = isVendorClient ? kVendorClientState: state;
3231
Ruben Brunkcc776712015-02-17 20:18:47 -08003232 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003233 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08003234}
3235
3236CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3237 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
3238 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00003239 partial->getConflicting(), partial->getPriority().getScore(),
3240 partial->getOwnerId(), partial->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08003241}
3242
3243// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07003244
3245static const int kDumpLockRetries = 50;
3246static const int kDumpLockSleep = 60000;
3247
3248static bool tryLock(Mutex& mutex)
3249{
3250 bool locked = false;
3251 for (int i = 0; i < kDumpLockRetries; ++i) {
3252 if (mutex.tryLock() == NO_ERROR) {
3253 locked = true;
3254 break;
3255 }
3256 usleep(kDumpLockSleep);
3257 }
3258 return locked;
3259}
3260
3261status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003262 ATRACE_CALL();
3263
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003264 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003265 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003266 CameraThreadState::getCallingPid(),
3267 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003268 return NO_ERROR;
3269 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003270 bool locked = tryLock(mServiceLock);
3271 // failed to lock - CameraService is probably deadlocked
3272 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003273 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003274 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003275
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003276 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003277 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07003278
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003279 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003280 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08003281
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003282 if (locked) mServiceLock.unlock();
3283 return NO_ERROR;
3284 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003285 dprintf(fd, "\n== Service global info: ==\n\n");
3286 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003287 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07003288 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
3289 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003290 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
3291 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
3292 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003293 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003294 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
3295 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003296
3297 dumpEventLog(fd);
3298
3299 bool stateLocked = tryLock(mCameraStatesLock);
3300 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003301 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003302 }
3303
Emilian Peevbd8c5032018-02-14 23:05:40 +00003304 int argSize = args.size();
3305 for (int i = 0; i < argSize; i++) {
3306 if (args[i] == TagMonitor::kMonitorOption) {
3307 if (i + 1 < argSize) {
3308 mMonitorTags = String8(args[i + 1]);
3309 }
3310 break;
3311 }
3312 }
3313
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003314 for (auto& state : mCameraStates) {
3315 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003316
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003317 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003318
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003319 CameraParameters p = state.second->getShimParams();
3320 if (!p.isEmpty()) {
3321 dprintf(fd, " Camera1 API shim is using parameters:\n ");
3322 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003323 }
3324
3325 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08003326 if (clientDescriptor != nullptr) {
3327 dprintf(fd, " Device %s is open. Client instance dump:\n",
3328 cameraId.string());
3329 dprintf(fd, " Client priority score: %d state: %d\n",
3330 clientDescriptor->getPriority().getScore(),
3331 clientDescriptor->getPriority().getState());
3332 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
3333
3334 auto client = clientDescriptor->getValue();
3335 dprintf(fd, " Client package: %s\n",
3336 String8(client->getPackageName()).string());
3337
3338 client->dumpClient(fd, args);
3339 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003340 dprintf(fd, " Device %s is closed, no client instance\n",
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003341 cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003342 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003343
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003344 }
3345
3346 if (stateLocked) mCameraStatesLock.unlock();
3347
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003348 if (locked) mServiceLock.unlock();
3349
Emilian Peevf53f66e2017-04-11 14:29:43 +01003350 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003351
3352 dprintf(fd, "\n== Vendor tags: ==\n\n");
3353
3354 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
3355 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00003356 sp<VendorTagDescriptorCache> cache =
3357 VendorTagDescriptorCache::getGlobalVendorTagCache();
3358 if (cache == NULL) {
3359 dprintf(fd, "No vendor tags.\n");
3360 } else {
3361 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
3362 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003363 } else {
3364 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
3365 }
3366
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003367 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003368 dprintf(fd, "\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003369 camera3::CameraTraces::dump(fd, args);
3370
3371 // Process dump arguments, if any
3372 int n = args.size();
3373 String16 verboseOption("-v");
3374 String16 unreachableOption("--unreachable");
3375 for (int i = 0; i < n; i++) {
3376 if (args[i] == verboseOption) {
3377 // change logging level
3378 if (i + 1 >= n) continue;
3379 String8 levelStr(args[i+1]);
3380 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003381 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003382 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003383 } else if (args[i] == unreachableOption) {
3384 // Dump memory analysis
3385 // TODO - should limit be an argument parameter?
3386 UnreachableMemoryInfo info;
3387 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
3388 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003389 dprintf(fd, "\n== Unable to dump unreachable memory. "
3390 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003391 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003392 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003393 std::string s = info.ToString(/*log_contents*/ true);
3394 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003395 }
3396 }
3397 }
3398 return NO_ERROR;
3399}
3400
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003401void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003402 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003403
3404 Mutex::Autolock l(mLogLock);
3405 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003406 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003407 }
3408
3409 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003410 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003411 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003412 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003413 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003414 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003415}
3416
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003417void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003418 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003419 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
3420 if (mTorchClientMap[i] == who) {
3421 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003422 String8 cameraId = mTorchClientMap.keyAt(i);
3423 status_t res = mFlashlight->setTorchMode(cameraId, false);
3424 if (res) {
3425 ALOGE("%s: torch client died but couldn't turn off torch: "
3426 "%s (%d)", __FUNCTION__, strerror(-res), res);
3427 return;
3428 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003429 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003430 break;
3431 }
3432 }
3433}
3434
Ruben Brunkcc776712015-02-17 20:18:47 -08003435/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003436
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003437 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07003438 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
3439 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003440 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003441 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003442 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003443
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003444 // check torch client
3445 handleTorchClientBinderDied(who);
3446
3447 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08003448 if(!evictClientIdByRemote(who)) {
3449 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003450 return;
3451 }
3452
Ruben Brunkcc776712015-02-17 20:18:47 -08003453 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
3454 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003455}
3456
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003457void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003458 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08003459}
3460
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003461void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
3462 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003463 // Do not lock mServiceLock here or can get into a deadlock from
3464 // connect() -> disconnect -> updateStatus
3465
3466 auto state = getCameraState(cameraId);
3467
3468 if (state == nullptr) {
3469 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
3470 cameraId.string());
3471 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07003472 }
3473
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003474 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
3475 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3476 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3477 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
3478 return;
3479 }
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003480 bool supportsHAL3 = false;
3481 // supportsCameraApi also holds mInterfaceMutex, we can't call it in the
3482 // HIDL onStatusChanged wrapper call (we'll hold mStatusListenerLock and
3483 // mInterfaceMutex together, which can lead to deadlocks)
3484 binder::Status sRet =
3485 supportsCameraApi(String16(cameraId), hardware::ICameraService::API_VERSION_2,
3486 &supportsHAL3);
3487 if (!sRet.isOk()) {
3488 ALOGW("%s: Failed to determine if device supports HAL3 %s, supportsCameraApi call failed",
3489 __FUNCTION__, cameraId.string());
3490 return;
3491 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003492 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
3493 // of the listeners with both the mStatusStatus and mStatusListenerLock held
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003494 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind, &supportsHAL3]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003495 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003496
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003497 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003498 // Update torch status if it has a flash unit.
3499 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003500 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003501 if (getTorchStatusLocked(cameraId, &torchStatus) !=
3502 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003503 TorchModeStatus newTorchStatus =
3504 status == StatusInternal::PRESENT ?
3505 TorchModeStatus::AVAILABLE_OFF :
3506 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003507 if (torchStatus != newTorchStatus) {
3508 onTorchStatusChangedLocked(cameraId, newTorchStatus);
3509 }
3510 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003511 }
3512
3513 Mutex::Autolock lock(mStatusListenerLock);
3514
3515 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003516 bool isVendorListener = listener->isVendorListener();
3517 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
3518 listener->getListenerPid(), listener->getListenerUid()) ||
3519 (isVendorListener && !supportsHAL3)) {
3520 ALOGV("Skipping discovery callback for system-only camera/HAL1 device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003521 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003522 continue;
3523 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003524 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08003525 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08003526 }
3527 });
Igor Murashkincba2c162013-03-20 15:56:31 -07003528}
3529
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003530template<class Func>
3531void CameraService::CameraState::updateStatus(StatusInternal status,
3532 const String8& cameraId,
3533 std::initializer_list<StatusInternal> rejectSourceStates,
3534 Func onStatusUpdatedLocked) {
3535 Mutex::Autolock lock(mStatusLock);
3536 StatusInternal oldStatus = mStatus;
3537 mStatus = status;
3538
3539 if (oldStatus == status) {
3540 return;
3541 }
3542
3543 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
3544 cameraId.string(), oldStatus, status);
3545
3546 if (oldStatus == StatusInternal::NOT_PRESENT &&
3547 (status != StatusInternal::PRESENT &&
3548 status != StatusInternal::ENUMERATING)) {
3549
3550 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
3551 __FUNCTION__);
3552 mStatus = oldStatus;
3553 return;
3554 }
3555
3556 /**
3557 * Sometimes we want to conditionally do a transition.
3558 * For example if a client disconnects, we want to go to PRESENT
3559 * only if we weren't already in NOT_PRESENT or ENUMERATING.
3560 */
3561 for (auto& rejectStatus : rejectSourceStates) {
3562 if (oldStatus == rejectStatus) {
3563 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
3564 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
3565 mStatus = oldStatus;
3566 return;
3567 }
3568 }
3569
3570 onStatusUpdatedLocked(cameraId, status);
3571}
3572
Eino-Ville Talvalae8c96c72017-06-27 12:24:07 -07003573void CameraService::updateProxyDeviceState(int newState,
Emilian Peev573291c2018-02-10 02:10:56 +00003574 const String8& cameraId, int facing, const String16& clientName, int apiLevel) {
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003575 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
3576 if (proxyBinder == nullptr) return;
3577 String16 id(cameraId);
Emilian Peev573291c2018-02-10 02:10:56 +00003578 proxyBinder->notifyCameraState(id, newState, facing, clientName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003579}
3580
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003581status_t CameraService::getTorchStatusLocked(
3582 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003583 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003584 if (!status) {
3585 return BAD_VALUE;
3586 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003587 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3588 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003589 // invalid camera ID or the camera doesn't have a flash unit
3590 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003591 }
3592
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003593 *status = mTorchStatusMap.valueAt(index);
3594 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003595}
3596
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003597status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003598 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003599 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3600 if (index == NAME_NOT_FOUND) {
3601 return BAD_VALUE;
3602 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003603 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003604
3605 return OK;
3606}
3607
Svet Ganova453d0d2018-01-11 15:37:58 -08003608void CameraService::blockClientsForUid(uid_t uid) {
3609 const auto clients = mActiveClientManager.getAll();
3610 for (auto& current : clients) {
3611 if (current != nullptr) {
3612 const auto basicClient = current->getValue();
3613 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
3614 basicClient->block();
3615 }
3616 }
3617 }
3618}
3619
Michael Grooverd1d435a2018-12-18 17:39:42 -08003620void CameraService::blockAllClients() {
3621 const auto clients = mActiveClientManager.getAll();
3622 for (auto& current : clients) {
3623 if (current != nullptr) {
3624 const auto basicClient = current->getValue();
3625 if (basicClient.get() != nullptr) {
3626 basicClient->block();
3627 }
3628 }
3629 }
3630}
3631
Svet Ganova453d0d2018-01-11 15:37:58 -08003632// NOTE: This is a remote API - make sure all args are validated
3633status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
3634 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
3635 return PERMISSION_DENIED;
3636 }
3637 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
3638 return BAD_VALUE;
3639 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003640 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003641 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003642 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003643 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003644 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003645 return handleGetUidState(args, out, err);
3646 } else if (args.size() == 1 && args[0] == String16("help")) {
3647 printHelp(out);
3648 return NO_ERROR;
3649 }
3650 printHelp(err);
3651 return BAD_VALUE;
3652}
3653
3654status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003655 String16 packageName = args[1];
3656
Svet Ganova453d0d2018-01-11 15:37:58 -08003657 bool active = false;
3658 if (args[2] == String16("active")) {
3659 active = true;
3660 } else if ((args[2] != String16("idle"))) {
3661 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
3662 return BAD_VALUE;
3663 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003664
3665 int userId = 0;
3666 if (args.size() >= 5 && args[3] == String16("--user")) {
3667 userId = atoi(String8(args[4]));
3668 }
3669
3670 uid_t uid;
3671 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
3672 return BAD_VALUE;
3673 }
3674
3675 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08003676 return NO_ERROR;
3677}
3678
3679status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003680 String16 packageName = args[1];
3681
3682 int userId = 0;
3683 if (args.size() >= 4 && args[2] == String16("--user")) {
3684 userId = atoi(String8(args[3]));
3685 }
3686
3687 uid_t uid;
3688 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003689 return BAD_VALUE;
3690 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003691
3692 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08003693 return NO_ERROR;
3694}
3695
3696status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003697 String16 packageName = args[1];
3698
3699 int userId = 0;
3700 if (args.size() >= 4 && args[2] == String16("--user")) {
3701 userId = atoi(String8(args[3]));
3702 }
3703
3704 uid_t uid;
3705 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003706 return BAD_VALUE;
3707 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003708
3709 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003710 return dprintf(out, "active\n");
3711 } else {
3712 return dprintf(out, "idle\n");
3713 }
3714}
3715
3716status_t CameraService::printHelp(int out) {
3717 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07003718 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
3719 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
3720 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08003721 " help print this message\n");
3722}
3723
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003724int32_t CameraService::updateAudioRestriction() {
3725 Mutex::Autolock lock(mServiceLock);
3726 return updateAudioRestrictionLocked();
3727}
3728
3729int32_t CameraService::updateAudioRestrictionLocked() {
3730 int32_t mode = 0;
3731 // iterate through all active client
3732 for (const auto& i : mActiveClientManager.getAll()) {
3733 const auto clientSp = i->getValue();
3734 mode |= clientSp->getAudioRestriction();
3735 }
3736
3737 bool modeChanged = (mAudioRestriction != mode);
3738 mAudioRestriction = mode;
3739 if (modeChanged) {
3740 mAppOps.setCameraAudioRestriction(mode);
3741 }
3742 return mode;
3743}
3744
Mathias Agopian65ab4712010-07-14 17:59:35 -07003745}; // namespace android