blob: a02178e890de5b2c0b7753fd187ad084c00f6c7f [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,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800735 const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800736 int api1CameraId, int facing, int clientPid, uid_t clientUid, int servicePid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700737 int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
Ruben Brunkcc776712015-02-17 20:18:47 -0800738 /*out*/sp<BasicClient>* client) {
739
Ruben Brunkcc776712015-02-17 20:18:47 -0800740 if (halVersion < 0 || halVersion == deviceVersion) {
741 // Default path: HAL version is unspecified by caller, create CameraClient
742 // based on device version reported by the HAL.
743 switch(deviceVersion) {
744 case CAMERA_DEVICE_API_VERSION_1_0:
745 if (effectiveApiLevel == API_1) { // Camera1 API route
746 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800747 *client = new CameraClient(cameraService, tmp, packageName,
748 api1CameraId, facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700749 getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800750 } else { // Camera2 API route
751 ALOGW("Camera using old HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800752 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800753 "Camera device \"%s\" HAL version %d does not support camera2 API",
754 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800755 }
756 break;
Ruben Brunkcc776712015-02-17 20:18:47 -0800757 case CAMERA_DEVICE_API_VERSION_3_0:
758 case CAMERA_DEVICE_API_VERSION_3_1:
759 case CAMERA_DEVICE_API_VERSION_3_2:
760 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -0700761 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -0700762 case CAMERA_DEVICE_API_VERSION_3_5:
Ruben Brunkcc776712015-02-17 20:18:47 -0800763 if (effectiveApiLevel == API_1) { // Camera1 API route
764 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800765 *client = new Camera2Client(cameraService, tmp, packageName,
766 cameraId, api1CameraId,
767 facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700768 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800769 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800770 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
771 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
772 *client = new CameraDeviceClient(cameraService, tmp, packageName, cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -0800773 facing, clientPid, clientUid, servicePid);
774 }
775 break;
776 default:
777 // Should not be reachable
778 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800779 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800780 "Camera device \"%s\" has unknown HAL version %d",
781 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800782 }
783 } else {
784 // A particular HAL version is requested by caller. Create CameraClient
785 // based on the requested HAL version.
786 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
787 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
788 // Only support higher HAL version device opened as HAL1.0 device.
789 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800790 *client = new CameraClient(cameraService, tmp, packageName,
791 api1CameraId, facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700792 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800793 } else {
794 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
795 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
796 " opened as HAL %x device", halVersion, deviceVersion,
797 CAMERA_DEVICE_API_VERSION_1_0);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800798 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800799 "Camera device \"%s\" (HAL version %d) cannot be opened as HAL version %d",
800 cameraId.string(), deviceVersion, halVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800801 }
802 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800803 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800804}
805
Ruben Brunk6267b532015-04-30 17:44:07 -0700806String8 CameraService::toString(std::set<userid_t> intSet) {
807 String8 s("");
808 bool first = true;
809 for (userid_t i : intSet) {
810 if (first) {
811 s.appendFormat("%d", i);
812 first = false;
813 } else {
814 s.appendFormat(", %d", i);
815 }
816 }
817 return s;
818}
819
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800820int32_t CameraService::mapToInterface(TorchModeStatus status) {
821 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
822 switch (status) {
823 case TorchModeStatus::NOT_AVAILABLE:
824 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
825 break;
826 case TorchModeStatus::AVAILABLE_OFF:
827 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
828 break;
829 case TorchModeStatus::AVAILABLE_ON:
830 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
831 break;
832 default:
833 ALOGW("Unknown new flash status: %d", status);
834 }
835 return serviceStatus;
836}
837
838CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
839 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
840 switch (status) {
841 case CameraDeviceStatus::NOT_PRESENT:
842 serviceStatus = StatusInternal::NOT_PRESENT;
843 break;
844 case CameraDeviceStatus::PRESENT:
845 serviceStatus = StatusInternal::PRESENT;
846 break;
847 case CameraDeviceStatus::ENUMERATING:
848 serviceStatus = StatusInternal::ENUMERATING;
849 break;
850 default:
851 ALOGW("Unknown new HAL device status: %d", status);
852 }
853 return serviceStatus;
854}
855
856int32_t CameraService::mapToInterface(StatusInternal status) {
857 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
858 switch (status) {
859 case StatusInternal::NOT_PRESENT:
860 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
861 break;
862 case StatusInternal::PRESENT:
863 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
864 break;
865 case StatusInternal::ENUMERATING:
866 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
867 break;
868 case StatusInternal::NOT_AVAILABLE:
869 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
870 break;
871 case StatusInternal::UNKNOWN:
872 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
873 break;
874 default:
875 ALOGW("Unknown new internal device status: %d", status);
876 }
877 return serviceStatus;
878}
879
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800880Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -0700881 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700882
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800883 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -0800884 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800885 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800886 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800887 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800888 sp<ICameraClient>{nullptr}, id, cameraId,
889 static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800890 internalPackageName, uid, USE_CALLING_PID,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700891 API_1, /*shimUpdateOnly*/ true, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800892 ).isOk()) {
893 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -0700894 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800895 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700896}
897
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800898Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -0700899 /*out*/
900 CameraParameters* parameters) {
901
902 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
903
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800904 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -0700905
906 if (parameters == NULL) {
907 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800908 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700909 }
910
Ruben Brunkcc776712015-02-17 20:18:47 -0800911 String8 id = String8::format("%d", cameraId);
912
913 // Check if we already have parameters
914 {
915 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700916 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800917 auto cameraState = getCameraState(id);
918 if (cameraState == nullptr) {
919 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800920 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
921 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800922 }
923 CameraParameters p = cameraState->getShimParams();
924 if (!p.isEmpty()) {
925 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800926 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700927 }
928 }
929
Jayant Chowdhary12361932018-08-27 14:46:13 -0700930 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -0800931 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -0700932 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800933 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800934 // Error already logged by callee
935 return ret;
936 }
937
938 // Check for parameters again
939 {
940 // Scope for service lock
941 Mutex::Autolock lock(mServiceLock);
942 auto cameraState = getCameraState(id);
943 if (cameraState == nullptr) {
944 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800945 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
946 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -0700947 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800948 CameraParameters p = cameraState->getShimParams();
949 if (!p.isEmpty()) {
950 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800951 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700952 }
953 }
954
Ruben Brunkcc776712015-02-17 20:18:47 -0800955 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
956 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800957 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700958}
959
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800960// Can camera service trust the caller based on the calling UID?
961static bool isTrustedCallingUid(uid_t uid) {
962 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -0700963 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800964 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -0700965 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800966 return true;
967 default:
968 return false;
969 }
970}
971
Nicholas Sauera3620332019-04-03 14:05:17 -0700972static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
973 PermissionController pc;
974 uid = pc.getPackageUid(packageName, 0);
975 if (uid <= 0) {
976 ALOGE("Unknown package: '%s'", String8(packageName).string());
977 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
978 return BAD_VALUE;
979 }
980
981 if (userId < 0) {
982 ALOGE("Invalid user: %d", userId);
983 dprintf(err, "Invalid user: %d\n", userId);
984 return BAD_VALUE;
985 }
986
987 uid = multiuser_get_uid(userId, uid);
988 return NO_ERROR;
989}
990
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800991Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -0700992 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
993 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -0500994
Alex Deymo9c2a2c22016-08-25 11:59:14 -0700995#ifdef __BRILLO__
996 UNUSED(clientName8);
997 UNUSED(clientUid);
998 UNUSED(clientPid);
999 UNUSED(originalClientPid);
1000#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001001 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1002 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001003 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001004 return allowed;
1005 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001006#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001007
Jayant Chowdhary12361932018-08-27 14:46:13 -07001008 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001009
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001010 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001011 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1012 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001013 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1014 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001015 }
1016
Ruben Brunkcc776712015-02-17 20:18:47 -08001017 if (getCameraState(cameraId) == nullptr) {
1018 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1019 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001020 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1021 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001022 }
1023
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001024 status_t err = checkIfDeviceIsUsable(cameraId);
1025 if (err != NO_ERROR) {
1026 switch(err) {
1027 case -ENODEV:
1028 case -EBUSY:
1029 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1030 "No camera device with ID \"%s\" currently available", cameraId.string());
1031 default:
1032 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1033 "Unknown error connecting to ID \"%s\"", cameraId.string());
1034 }
1035 }
1036 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001037}
1038
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001039Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001040 const String8& clientName8, int& clientUid, int& clientPid,
1041 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001042 int callingPid = CameraThreadState::getCallingPid();
1043 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001044
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001045 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001046 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001047 clientUid = callingUid;
1048 } else if (!isTrustedCallingUid(callingUid)) {
1049 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1050 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001051 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1052 "Untrusted caller (calling PID %d, UID %d) trying to "
1053 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1054 callingPid, callingUid, cameraId.string(),
1055 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001056 }
1057
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001058 // Check if we can trust clientPid
1059 if (clientPid == USE_CALLING_PID) {
1060 clientPid = callingPid;
1061 } else if (!isTrustedCallingUid(callingUid)) {
1062 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1063 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001064 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1065 "Untrusted caller (calling PID %d, UID %d) trying to "
1066 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1067 callingPid, callingUid, cameraId.string(),
1068 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001069 }
1070
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001071 if (shouldRejectSystemCameraConnection(cameraId)) {
1072 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1073 cameraId.c_str());
1074 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1075 "available", cameraId.string());
1076 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001077 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1078 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1079 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1080 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1081 "found while trying to query device kind", cameraId.string());
1082
1083 }
1084
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001085 // If it's not calling from cameraserver, check the permission if the
1086 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1087 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001088 if (callingPid != getpid() &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001089 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001090 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001091 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001092 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1093 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1094 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001095 }
1096
Svet Ganova453d0d2018-01-11 15:37:58 -08001097 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001098 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001099 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001100 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1101 clientPid, clientUid);
1102 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001103 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1104 "calling UID %d proc state %" PRId32 ")",
1105 clientName8.string(), clientUid, clientPid, cameraId.string(),
1106 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001107 }
1108
Michael Grooverd1d435a2018-12-18 17:39:42 -08001109 // If sensor privacy is enabled then prevent access to the camera
1110 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1111 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1112 return STATUS_ERROR_FMT(ERROR_DISABLED,
1113 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1114 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1115 }
1116
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001117 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1118 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001119 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001120 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001121
Ruben Brunk6267b532015-04-30 17:44:07 -07001122 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001123
Ruben Brunka8ca9152015-04-07 14:23:40 -07001124 // Only allow clients who are being used by the current foreground device user, unless calling
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001125 // from our own process OR the caller is using the cameraserver's HIDL interface.
1126 if (!hardware::IPCThreadState::self()->isServingCall() && callingPid != getpid() &&
1127 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001128 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1129 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1130 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001131 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1132 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1133 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001134 }
1135
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001136 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001137}
1138
1139status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1140 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001141 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001142 if (cameraState == nullptr) {
1143 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1144 cameraId.string());
1145 return -ENODEV;
1146 }
1147
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001148 StatusInternal currentStatus = cameraState->getStatus();
1149 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001150 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1151 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001152 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001153 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001154 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1155 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001156 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001157 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001158
Ruben Brunkcc776712015-02-17 20:18:47 -08001159 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001160}
1161
Ruben Brunkcc776712015-02-17 20:18:47 -08001162void CameraService::finishConnectLocked(const sp<BasicClient>& client,
1163 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001164
Ruben Brunkcc776712015-02-17 20:18:47 -08001165 // Make a descriptor for the incoming client
1166 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
1167 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1168
1169 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1170 String8(client->getPackageName()));
1171
1172 if (evicted.size() > 0) {
1173 // This should never happen - clients should already have been removed in disconnect
1174 for (auto& i : evicted) {
1175 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1176 __FUNCTION__, i->getKey().string());
1177 }
1178
1179 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1180 __FUNCTION__);
1181 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001182
1183 // And register a death notification for the client callback. Do
1184 // this last to avoid Binder policy where a nested Binder
1185 // transaction might be pre-empted to service the client death
1186 // notification if the client process dies before linkToDeath is
1187 // invoked.
1188 sp<IBinder> remoteCallback = client->getRemote();
1189 if (remoteCallback != nullptr) {
1190 remoteCallback->linkToDeath(this);
1191 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001192}
1193
1194status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1195 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
1196 /*out*/
1197 sp<BasicClient>* client,
1198 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001199 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001200 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001201 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001202 DescriptorPtr clientDescriptor;
1203 {
1204 if (effectiveApiLevel == API_1) {
1205 // If we are using API1, any existing client for this camera ID with the same remote
1206 // should be returned rather than evicted to allow MediaRecorder to work properly.
1207
1208 auto current = mActiveClientManager.get(cameraId);
1209 if (current != nullptr) {
1210 auto clientSp = current->getValue();
1211 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001212 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1213 ALOGW("CameraService connect called from same client, but with a different"
1214 " API level, evicting prior client...");
1215 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001216 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001217 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001218 *client = clientSp;
1219 return NO_ERROR;
1220 }
1221 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001222 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001223 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001224
Ruben Brunkcc776712015-02-17 20:18:47 -08001225 // Get current active client PIDs
1226 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1227 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001228
Emilian Peev8131a262017-02-01 12:33:43 +00001229 std::vector<int> priorityScores(ownerPids.size());
1230 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001231
Emilian Peev8131a262017-02-01 12:33:43 +00001232 // Get priority scores of all active PIDs
1233 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1234 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1235 /*out*/&priorityScores[0]);
1236 if (err != OK) {
1237 ALOGE("%s: Priority score query failed: %d",
1238 __FUNCTION__, err);
1239 return err;
1240 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001241
Ruben Brunkcc776712015-02-17 20:18:47 -08001242 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001243 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001244 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001245 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001246 resource_policy::ClientPriority(priorityScores[i], states[i],
1247 /* isVendorClient won't get copied over*/ false));
Ruben Brunkcc776712015-02-17 20:18:47 -08001248 }
1249 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001250
Ruben Brunkcc776712015-02-17 20:18:47 -08001251 // Get state for the given cameraId
1252 auto state = getCameraState(cameraId);
1253 if (state == nullptr) {
1254 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1255 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001256 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001257 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001258 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001259
1260 // Make descriptor for incoming client
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001261 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001262 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1263 state->getConflicting(),
Emilian Peev8131a262017-02-01 12:33:43 +00001264 priorityScores[priorityScores.size() - 1],
1265 clientPid,
1266 states[states.size() - 1]);
Ruben Brunkcc776712015-02-17 20:18:47 -08001267
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001268 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1269
Ruben Brunkcc776712015-02-17 20:18:47 -08001270 // Find clients that would be evicted
1271 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1272
1273 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1274 // background, so we cannot do evictions
1275 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1276 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1277 " priority).", clientPid);
1278
1279 sp<BasicClient> clientSp = clientDescriptor->getValue();
1280 String8 curTime = getFormattedCurrentTime();
1281 auto incompatibleClients =
1282 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1283
1284 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001285 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001286 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001287 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001288
1289 for (auto& i : incompatibleClients) {
1290 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001291 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1292 i->getKey().string(),
1293 String8{i->getValue()->getPackageName()}.string(),
1294 i->getOwnerId(), i->getPriority().getScore(),
1295 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001296 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001297 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001298 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001299 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001300 }
1301
1302 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001303 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001304 mEventLog.add(msg);
1305
1306 return -EBUSY;
1307 }
1308
1309 for (auto& i : evicted) {
1310 sp<BasicClient> clientSp = i->getValue();
1311 if (clientSp.get() == nullptr) {
1312 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1313
1314 // TODO: Remove this
1315 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1316 __FUNCTION__);
1317 mActiveClientManager.remove(i);
1318 continue;
1319 }
1320
1321 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1322 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001323 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001324
Ruben Brunkcc776712015-02-17 20:18:47 -08001325 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001326 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001327 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1328 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001329 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001330 i->getOwnerId(), i->getPriority().getScore(),
1331 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001332 packageName.string(), clientPid, clientPriority.getScore(),
1333 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001334
1335 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001336 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001337 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001338 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001339 }
1340
Ruben Brunkcc776712015-02-17 20:18:47 -08001341 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1342 // other clients from connecting in mServiceLockWrapper if held
1343 mServiceLock.unlock();
1344
1345 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001346 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001347
1348 // Destroy evicted clients
1349 for (auto& i : evictedClients) {
1350 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001351 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001352 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001353
Jayant Chowdhary12361932018-08-27 14:46:13 -07001354 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001355
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001356 for (const auto& i : evictedClients) {
1357 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1358 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1359 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1360 if (ret == TIMED_OUT) {
1361 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1362 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1363 mActiveClientManager.toString().string());
1364 return -EBUSY;
1365 }
1366 if (ret != NO_ERROR) {
1367 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1368 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1369 ret, mActiveClientManager.toString().string());
1370 return ret;
1371 }
1372 }
1373
1374 evictedClients.clear();
1375
Ruben Brunkcc776712015-02-17 20:18:47 -08001376 // Once clients have been disconnected, relock
1377 mServiceLock.lock();
1378
1379 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1380 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1381 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001382 }
1383
Ruben Brunkcc776712015-02-17 20:18:47 -08001384 *partial = clientDescriptor;
1385 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001386}
1387
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001388Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001389 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001390 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001391 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001392 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001393 int clientPid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001394 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001395 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001396
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001397 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001398 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001399
1400 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001401 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001402 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001403 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, clientUid, clientPid, API_1,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001404 /*shimUpdateOnly*/ false, /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001405
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001406 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001407 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001408 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001409 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001410 }
1411
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001412 *device = client;
1413 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001414}
1415
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001416Status CameraService::connectLegacy(
Zhijun Heb10cdad2014-06-16 16:38:35 -07001417 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001418 int api1CameraId, int halVersion,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001419 const String16& clientPackageName,
Zhijun Heb10cdad2014-06-16 16:38:35 -07001420 int clientUid,
1421 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001422 sp<ICamera>* device) {
Zhijun Heb10cdad2014-06-16 16:38:35 -07001423
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001424 ATRACE_CALL();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001425 String8 id = cameraIdIntToStr(api1CameraId);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001426
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001427 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001428 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001429 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId, halVersion,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001430 clientPackageName, clientUid, USE_CALLING_PID, API_1, /*shimUpdateOnly*/ false,
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001431 /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001432
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001433 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001434 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001435 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001436 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001437 }
1438
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001439 *device = client;
1440 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001441}
1442
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001443bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1444 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001445 // If the client is not a vendor client, don't add listener if
1446 // a) the camera is a publicly hidden secure camera OR
1447 // b) the camera is a system only camera and the client doesn't
1448 // have android.permission.SYSTEM_CAMERA permissions.
1449 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1450 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1451 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001452 return true;
1453 }
1454 return false;
1455}
1456
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001457bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1458 // Rules for rejection:
1459 // 1) If cameraserver tries to access this camera device, accept the
1460 // connection.
1461 // 2) The camera device is a publicly hidden secure camera device AND some
1462 // component is trying to access it on a non-hwbinder thread (generally a non HAL client),
1463 // reject it.
1464 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1465 // and the serving thread is a non hwbinder thread, the client must have
1466 // android.permission.SYSTEM_CAMERA permissions to connect.
1467
1468 int cPid = CameraThreadState::getCallingPid();
1469 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001470 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1471 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
1472 ALOGE("%s: Invalid camera id %s, ", __FUNCTION__, cameraId.c_str());
1473 return true;
1474 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001475
1476 // (1) Cameraserver trying to connect, accept.
1477 if (CameraThreadState::getCallingPid() == getpid()) {
1478 return false;
1479 }
1480 // (2)
1481 if (!hardware::IPCThreadState::self()->isServingCall() &&
1482 systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
1483 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1484 return true;
1485 }
1486 // (3) Here we only check for permissions if it is a system only camera device. This is since
1487 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1488 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1489 // same behavior for system camera devices.
1490 if (!hardware::IPCThreadState::self()->isServingCall() &&
1491 systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1492 !hasPermissionsForSystemCamera(cPid, cUid)) {
1493 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1494 cameraId.c_str());
1495 return true;
1496 }
1497
1498 return false;
1499}
1500
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001501Status CameraService::connectDevice(
1502 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001503 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001504 const String16& clientPackageName,
Ruben Brunkcc776712015-02-17 20:18:47 -08001505 int clientUid,
1506 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001507 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001508
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001509 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001510 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001511 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001512 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001513 String16 clientPackageNameAdj = clientPackageName;
1514 if (hardware::IPCThreadState::self()->isServingCall()) {
1515 std::string vendorClient =
1516 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1517 clientPackageNameAdj = String16(vendorClient.c_str());
1518 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001519 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001520 /*api1CameraId*/-1,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001521 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageNameAdj,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001522 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001523
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001524 if(!ret.isOk()) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001525 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageNameAdj),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001526 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001527 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001528 }
1529
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001530 *device = client;
1531 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001532}
1533
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001534template<class CALLBACK, class CLIENT>
1535Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001536 int api1CameraId, int halVersion, const String16& clientPackageName, int clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001537 int clientPid, apiLevel effectiveApiLevel, bool shimUpdateOnly,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001538 /*out*/sp<CLIENT>& device) {
1539 binder::Status ret = binder::Status::ok();
1540
1541 String8 clientName8(clientPackageName);
1542
1543 int originalClientPid = 0;
1544
1545 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) for HAL version %s and "
1546 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
1547 (halVersion == -1) ? "default" : std::to_string(halVersion).c_str(),
1548 static_cast<int>(effectiveApiLevel));
1549
1550 sp<CLIENT> client = nullptr;
1551 {
1552 // Acquire mServiceLock and prevent other clients from connecting
1553 std::unique_ptr<AutoConditionLock> lock =
1554 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1555
1556 if (lock == nullptr) {
1557 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1558 , clientPid);
1559 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1560 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1561 cameraId.string(), clientName8.string(), clientPid);
1562 }
1563
1564 // Enforce client permissions and do basic sanity checks
1565 if(!(ret = validateConnectLocked(cameraId, clientName8,
1566 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1567 return ret;
1568 }
1569
1570 // Check the shim parameters after acquiring lock, if they have already been updated and
1571 // we were doing a shim update, return immediately
1572 if (shimUpdateOnly) {
1573 auto cameraState = getCameraState(cameraId);
1574 if (cameraState != nullptr) {
1575 if (!cameraState->getShimParams().isEmpty()) return ret;
1576 }
1577 }
1578
1579 status_t err;
1580
1581 sp<BasicClient> clientTmp = nullptr;
1582 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1583 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
1584 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
1585 /*out*/&partial)) != NO_ERROR) {
1586 switch (err) {
1587 case -ENODEV:
1588 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1589 "No camera device with ID \"%s\" currently available",
1590 cameraId.string());
1591 case -EBUSY:
1592 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1593 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1594 cameraId.string());
1595 default:
1596 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1597 "Unexpected error %s (%d) opening camera \"%s\"",
1598 strerror(-err), err, cameraId.string());
1599 }
1600 }
1601
1602 if (clientTmp.get() != nullptr) {
1603 // Handle special case for API1 MediaRecorder where the existing client is returned
1604 device = static_cast<CLIENT*>(clientTmp.get());
1605 return ret;
1606 }
1607
1608 // give flashlight a chance to close devices if necessary.
1609 mFlashlight->prepareDeviceOpen(cameraId);
1610
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001611 int facing = -1;
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001612 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001613 if (facing == -1) {
1614 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1615 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1616 "Unable to get camera device \"%s\" facing", cameraId.string());
1617 }
1618
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001619 sp<BasicClient> tmp = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001620 if(!(ret = makeClient(this, cameraCb, clientPackageName,
1621 cameraId, api1CameraId, facing,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001622 clientPid, clientUid, getpid(),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001623 halVersion, deviceVersion, effectiveApiLevel,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001624 /*out*/&tmp)).isOk()) {
1625 return ret;
1626 }
1627 client = static_cast<CLIENT*>(tmp.get());
1628
1629 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1630 __FUNCTION__);
1631
Emilian Peevbd8c5032018-02-14 23:05:40 +00001632 err = client->initialize(mCameraProviderManager, mMonitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001633 if (err != OK) {
1634 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001635 // Errors could be from the HAL module open call or from AppOpsManager
1636 switch(err) {
1637 case BAD_VALUE:
1638 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1639 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1640 case -EBUSY:
1641 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1642 "Camera \"%s\" is already open", cameraId.string());
1643 case -EUSERS:
1644 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1645 "Too many cameras already open, cannot open camera \"%s\"",
1646 cameraId.string());
1647 case PERMISSION_DENIED:
1648 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1649 "No permission to open camera \"%s\"", cameraId.string());
1650 case -EACCES:
1651 return STATUS_ERROR_FMT(ERROR_DISABLED,
1652 "Camera \"%s\" disabled by policy", cameraId.string());
1653 case -ENODEV:
1654 default:
1655 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1656 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1657 strerror(-err), err);
1658 }
1659 }
1660
1661 // Update shim paremeters for legacy clients
1662 if (effectiveApiLevel == API_1) {
1663 // Assume we have always received a Client subclass for API1
1664 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1665 String8 rawParams = shimClient->getParameters();
1666 CameraParameters params(rawParams);
1667
1668 auto cameraState = getCameraState(cameraId);
1669 if (cameraState != nullptr) {
1670 cameraState->setShimParams(params);
1671 } else {
1672 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1673 __FUNCTION__, cameraId.string());
1674 }
1675 }
1676
1677 if (shimUpdateOnly) {
1678 // If only updating legacy shim parameters, immediately disconnect client
1679 mServiceLock.unlock();
1680 client->disconnect();
1681 mServiceLock.lock();
1682 } else {
1683 // Otherwise, add client to active clients list
1684 finishConnectLocked(client, partial);
1685 }
1686 } // lock is destroyed, allow further connect calls
1687
1688 // Important: release the mutex here so the client can call back into the service from its
1689 // destructor (can be at the end of the call)
1690 device = client;
1691 return ret;
1692}
1693
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001694Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001695 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001696 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001697
1698 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001699 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001700 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001701 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1702 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001703 }
1704
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001705 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07001706 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001707
1708 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001709 auto state = getCameraState(id);
1710 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001711 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001712 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1713 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001714 }
1715
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001716 StatusInternal cameraStatus = state->getStatus();
1717 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001718 cameraStatus != StatusInternal::NOT_AVAILABLE) {
1719 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001720 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1721 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001722 }
1723
1724 {
1725 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001726 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001727 status_t err = getTorchStatusLocked(id, &status);
1728 if (err != OK) {
1729 if (err == NAME_NOT_FOUND) {
1730 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1731 "Camera \"%s\" does not have a flash unit", id.string());
1732 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001733 ALOGE("%s: getting current torch status failed for camera %s",
1734 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001735 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1736 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
1737 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001738 }
1739
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001740 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001741 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001742 ALOGE("%s: torch mode of camera %s is not available because "
1743 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001744 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1745 "Torch for camera \"%s\" is not available due to an existing camera user",
1746 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001747 } else {
1748 ALOGE("%s: torch mode of camera %s is not available due to "
1749 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001750 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1751 "Torch for camera \"%s\" is not available due to insufficient resources",
1752 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001753 }
1754 }
1755 }
1756
Ruben Brunk99e69712015-05-26 17:25:07 -07001757 {
1758 // Update UID map - this is used in the torch status changed callbacks, so must be done
1759 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001760 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001761 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1762 mTorchUidMap[id].first = uid;
1763 mTorchUidMap[id].second = uid;
1764 } else {
1765 // Set the pending UID
1766 mTorchUidMap[id].first = uid;
1767 }
1768 }
1769
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001770 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001771
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001772 if (err != OK) {
1773 int32_t errorCode;
1774 String8 msg;
1775 switch (err) {
1776 case -ENOSYS:
1777 msg = String8::format("Camera \"%s\" has no flashlight",
1778 id.string());
1779 errorCode = ERROR_ILLEGAL_ARGUMENT;
1780 break;
1781 default:
1782 msg = String8::format(
1783 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1784 id.string(), enabled, strerror(-err), err);
1785 errorCode = ERROR_INVALID_OPERATION;
1786 }
1787 ALOGE("%s: %s", __FUNCTION__, msg.string());
1788 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001789 }
1790
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001791 {
1792 // update the link to client's death
1793 Mutex::Autolock al(mTorchClientMapMutex);
1794 ssize_t index = mTorchClientMap.indexOfKey(id);
1795 if (enabled) {
1796 if (index == NAME_NOT_FOUND) {
1797 mTorchClientMap.add(id, clientBinder);
1798 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001799 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001800 mTorchClientMap.replaceValueAt(index, clientBinder);
1801 }
1802 clientBinder->linkToDeath(this);
1803 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001804 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001805 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001806 }
1807
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07001808 int clientPid = CameraThreadState::getCallingPid();
1809 const char *id_cstr = id.c_str();
1810 const char *torchState = enabled ? "on" : "off";
1811 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
1812 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001813 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001814}
1815
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001816Status CameraService::notifySystemEvent(int32_t eventId,
1817 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001818 const int pid = CameraThreadState::getCallingPid();
1819 const int selfPid = getpid();
1820
1821 // Permission checks
1822 if (pid != selfPid) {
1823 // Ensure we're being called by system_server, or similar process with
1824 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001825 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001826 const int uid = CameraThreadState::getCallingUid();
1827 ALOGE("Permission Denial: cannot send updates to camera service about system"
1828 " events from pid=%d, uid=%d", pid, uid);
1829 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09001830 "No permission to send updates to camera service about system events"
1831 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001832 }
1833 }
1834
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001835 ATRACE_CALL();
1836
Ruben Brunk36597b22015-03-20 22:15:57 -07001837 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001838 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001839 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07001840 // from a system server crash
1841 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08001842 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001843 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07001844 break;
1845 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001846 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07001847 default: {
1848 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1849 eventId);
1850 break;
1851 }
1852 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001853 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07001854}
1855
Emilian Peev53722fa2019-02-22 17:47:20 -08001856void CameraService::notifyMonitoredUids() {
1857 Mutex::Autolock lock(mStatusListenerLock);
1858
1859 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001860 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08001861 if (!ret.isOk()) {
1862 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
1863 ret.exceptionCode());
1864 }
1865 }
1866}
1867
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08001868Status CameraService::notifyDeviceStateChange(int64_t newState) {
1869 const int pid = CameraThreadState::getCallingPid();
1870 const int selfPid = getpid();
1871
1872 // Permission checks
1873 if (pid != selfPid) {
1874 // Ensure we're being called by system_server, or similar process with
1875 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001876 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08001877 const int uid = CameraThreadState::getCallingUid();
1878 ALOGE("Permission Denial: cannot send updates to camera service about device"
1879 " state changes from pid=%d, uid=%d", pid, uid);
1880 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1881 "No permission to send updates to camera service about device state"
1882 " changes from pid=%d, uid=%d", pid, uid);
1883 }
1884 }
1885
1886 ATRACE_CALL();
1887
1888 using hardware::camera::provider::V2_5::DeviceState;
1889 hardware::hidl_bitfield<DeviceState> newDeviceState{};
1890 if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
1891 newDeviceState |= DeviceState::BACK_COVERED;
1892 }
1893 if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
1894 newDeviceState |= DeviceState::FRONT_COVERED;
1895 }
1896 if (newState & ICameraService::DEVICE_STATE_FOLDED) {
1897 newDeviceState |= DeviceState::FOLDED;
1898 }
1899 // Only map vendor bits directly
1900 uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
1901 newDeviceState |= vendorBits;
1902
1903 ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
1904 Mutex::Autolock l(mServiceLock);
1905 mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
1906
1907 return Status::ok();
1908}
1909
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001910Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
1911 /*out*/
1912 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001913 return addListenerHelper(listener, cameraStatuses);
1914}
1915
1916Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
1917 /*out*/
1918 std::vector<hardware::CameraStatus> *cameraStatuses,
1919 bool isVendorListener) {
1920
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001921 ATRACE_CALL();
1922
Igor Murashkinbfc99152013-02-27 12:55:20 -08001923 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08001924
Ruben Brunk3450ba72015-06-16 11:00:37 -07001925 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001926 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001927 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001928 }
1929
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001930 auto clientUid = CameraThreadState::getCallingUid();
1931 auto clientPid = CameraThreadState::getCallingPid();
1932
Igor Murashkinbfc99152013-02-27 12:55:20 -08001933 Mutex::Autolock lock(mServiceLock);
1934
Ruben Brunkcc776712015-02-17 20:18:47 -08001935 {
1936 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08001937 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001938 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001939 ALOGW("%s: Tried to add listener %p which was already subscribed",
1940 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001941 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08001942 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001943 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001944
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001945 sp<ServiceListener> serviceListener =
1946 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08001947 auto ret = serviceListener->initialize();
1948 if (ret != NO_ERROR) {
1949 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
1950 strerror(-ret), ret);
1951 ALOGE("%s: %s", __FUNCTION__, msg.string());
1952 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
1953 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001954 // The listener still needs to be added to the list of listeners, regardless of what
1955 // permissions the listener process has / whether it is a vendor listener. Since it might be
1956 // eligible to listen to other camera ids.
1957 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08001958 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08001959 }
1960
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001961 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07001962 {
Ruben Brunkcc776712015-02-17 20:18:47 -08001963 Mutex::Autolock lock(mCameraStatesLock);
1964 for (auto& i : mCameraStates) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001965 cameraStatuses->emplace_back(i.first, mapToInterface(i.second->getStatus()));
Igor Murashkincba2c162013-03-20 15:56:31 -07001966 }
1967 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001968 // Remove the camera statuses that should be hidden from the client, we do
1969 // this after collecting the states in order to avoid holding
1970 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
1971 // the same time.
1972 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
1973 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
1974 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1975 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
1976 ALOGE("%s: Invalid camera id %s, skipping status update",
1977 __FUNCTION__, s.cameraId.c_str());
1978 return true;
1979 }
1980 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
1981 clientUid);}), cameraStatuses->end());
1982
Igor Murashkincba2c162013-03-20 15:56:31 -07001983
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001984 /*
1985 * Immediately signal current torch status to this listener only
1986 * This may be a subset of all the devices, so don't include it in the response directly
1987 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001988 {
1989 Mutex::Autolock al(mTorchStatusMutex);
1990 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001991 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001992 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001993 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001994 }
1995
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001996 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08001997}
Ruben Brunkcc776712015-02-17 20:18:47 -08001998
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001999Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002000 ATRACE_CALL();
2001
Igor Murashkinbfc99152013-02-27 12:55:20 -08002002 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2003
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002004 if (listener == 0) {
2005 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002006 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002007 }
2008
Igor Murashkinbfc99152013-02-27 12:55:20 -08002009 Mutex::Autolock lock(mServiceLock);
2010
Ruben Brunkcc776712015-02-17 20:18:47 -08002011 {
2012 Mutex::Autolock lock(mStatusListenerLock);
2013 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002014 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2015 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2016 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002017 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002018 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002019 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002020 }
2021 }
2022
2023 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2024 __FUNCTION__, listener.get());
2025
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002026 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002027}
2028
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002029Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002030
2031 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002032 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2033
2034 if (parameters == NULL) {
2035 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002036 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002037 }
2038
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002039 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002040
2041 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002042 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002043 // Error logged by caller
2044 return ret;
2045 }
2046
2047 String8 shimParamsString8 = shimParams.flatten();
2048 String16 shimParamsString16 = String16(shimParamsString8);
2049
2050 *parameters = shimParamsString16;
2051
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002052 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002053}
2054
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002055Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2056 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002057 ATRACE_CALL();
2058
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002059 const String8 id = String8(cameraId);
2060
2061 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002062
2063 switch (apiVersion) {
2064 case API_VERSION_1:
2065 case API_VERSION_2:
2066 break;
2067 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002068 String8 msg = String8::format("Unknown API version %d", apiVersion);
2069 ALOGE("%s: %s", __FUNCTION__, msg.string());
2070 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002071 }
2072
Emilian Peev28ad2ea2017-02-07 16:14:32 +00002073 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002074 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002075 case CAMERA_DEVICE_API_VERSION_1_0:
2076 case CAMERA_DEVICE_API_VERSION_3_0:
2077 case CAMERA_DEVICE_API_VERSION_3_1:
2078 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002079 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2080 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002081 *isSupported = false;
2082 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002083 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2084 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002085 *isSupported = true;
2086 }
2087 break;
2088 case CAMERA_DEVICE_API_VERSION_3_2:
2089 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07002090 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002091 case CAMERA_DEVICE_API_VERSION_3_5:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002092 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2093 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002094 *isSupported = true;
2095 break;
2096 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002097 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002098 ALOGE("%s: %s", __FUNCTION__, msg.string());
2099 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002100 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002101 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002102 String8 msg = String8::format("Unknown device version %x for device %s",
2103 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002104 ALOGE("%s: %s", __FUNCTION__, msg.string());
2105 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2106 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002107 }
2108
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002109 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002110}
2111
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002112Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2113 /*out*/ bool *isSupported) {
2114 ATRACE_CALL();
2115
2116 const String8 id = String8(cameraId);
2117
2118 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2119 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2120
2121 return Status::ok();
2122}
2123
Ruben Brunkcc776712015-02-17 20:18:47 -08002124void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002125 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002126 for (auto& i : mActiveClientManager.getAll()) {
2127 auto clientSp = i->getValue();
2128 if (clientSp.get() == client) {
2129 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002130 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002131 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002132 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002133}
2134
Ruben Brunkcc776712015-02-17 20:18:47 -08002135bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002136 bool ret = false;
2137 {
2138 // Acquire mServiceLock and prevent other clients from connecting
2139 std::unique_ptr<AutoConditionLock> lock =
2140 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002141
Igor Murashkin634a5152013-02-20 17:15:11 -08002142
Ruben Brunkcc776712015-02-17 20:18:47 -08002143 std::vector<sp<BasicClient>> evicted;
2144 for (auto& i : mActiveClientManager.getAll()) {
2145 auto clientSp = i->getValue();
2146 if (clientSp.get() == nullptr) {
2147 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2148 mActiveClientManager.remove(i);
2149 continue;
2150 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002151 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002152 mActiveClientManager.remove(i);
2153 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002154
Ruben Brunkcc776712015-02-17 20:18:47 -08002155 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002156 clientSp->notifyError(
2157 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002158 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002159 }
2160 }
2161
Ruben Brunkcc776712015-02-17 20:18:47 -08002162 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2163 // other clients from connecting in mServiceLockWrapper if held
2164 mServiceLock.unlock();
2165
Ruben Brunk36597b22015-03-20 22:15:57 -07002166 // Do not clear caller identity, remote caller should be client proccess
2167
Ruben Brunkcc776712015-02-17 20:18:47 -08002168 for (auto& i : evicted) {
2169 if (i.get() != nullptr) {
2170 i->disconnect();
2171 ret = true;
2172 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002173 }
2174
Ruben Brunkcc776712015-02-17 20:18:47 -08002175 // Reacquire mServiceLock
2176 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002177
Ruben Brunkcc776712015-02-17 20:18:47 -08002178 } // lock is destroyed, allow further connect calls
2179
2180 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002181}
2182
Ruben Brunkcc776712015-02-17 20:18:47 -08002183std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2184 const String8& cameraId) const {
2185 std::shared_ptr<CameraState> state;
2186 {
2187 Mutex::Autolock lock(mCameraStatesLock);
2188 auto iter = mCameraStates.find(cameraId);
2189 if (iter != mCameraStates.end()) {
2190 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002191 }
2192 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002193 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002194}
2195
Ruben Brunkcc776712015-02-17 20:18:47 -08002196sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2197 // Remove from active clients list
2198 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2199 if (clientDescriptorPtr == nullptr) {
2200 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2201 cameraId.string());
2202 return sp<BasicClient>{nullptr};
2203 }
2204
2205 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07002206}
2207
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002208void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002209 // Acquire mServiceLock and prevent other clients from connecting
2210 std::unique_ptr<AutoConditionLock> lock =
2211 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2212
Ruben Brunk6267b532015-04-30 17:44:07 -07002213 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002214 for (size_t i = 0; i < newUserIds.size(); i++) {
2215 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002216 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002217 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002218 return;
2219 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002220 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002221 }
2222
Ruben Brunka8ca9152015-04-07 14:23:40 -07002223
Ruben Brunk6267b532015-04-30 17:44:07 -07002224 if (newAllowedUsers == mAllowedUsers) {
2225 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2226 return;
2227 }
2228
2229 logUserSwitch(mAllowedUsers, newAllowedUsers);
2230
2231 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002232
2233 // Current user has switched, evict all current clients.
2234 std::vector<sp<BasicClient>> evicted;
2235 for (auto& i : mActiveClientManager.getAll()) {
2236 auto clientSp = i->getValue();
2237
2238 if (clientSp.get() == nullptr) {
2239 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2240 continue;
2241 }
2242
Ruben Brunk6267b532015-04-30 17:44:07 -07002243 // Don't evict clients that are still allowed.
2244 uid_t clientUid = clientSp->getClientUid();
2245 userid_t clientUserId = multiuser_get_user_id(clientUid);
2246 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2247 continue;
2248 }
2249
Ruben Brunk36597b22015-03-20 22:15:57 -07002250 evicted.push_back(clientSp);
2251
2252 String8 curTime = getFormattedCurrentTime();
2253
2254 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2255 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002256
Ruben Brunk36597b22015-03-20 22:15:57 -07002257 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002258 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002259 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2260 " to user switch.", i->getKey().string(),
2261 String8{clientSp->getPackageName()}.string(),
2262 i->getOwnerId(), i->getPriority().getScore(),
2263 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002264
2265 }
2266
2267 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2268 // blocking other clients from connecting in mServiceLockWrapper if held.
2269 mServiceLock.unlock();
2270
2271 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002272 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002273
2274 for (auto& i : evicted) {
2275 i->disconnect();
2276 }
2277
Jayant Chowdhary12361932018-08-27 14:46:13 -07002278 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002279
2280 // Reacquire mServiceLock
2281 mServiceLock.lock();
2282}
Ruben Brunkcc776712015-02-17 20:18:47 -08002283
Ruben Brunka8ca9152015-04-07 14:23:40 -07002284void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002285 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002286 Mutex::Autolock l(mLogLock);
2287 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002288}
2289
Ruben Brunka8ca9152015-04-07 14:23:40 -07002290void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002291 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002292 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002293 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002294 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002295}
2296
2297void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002298 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002299 // Log the clients evicted
2300 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002301 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002302}
2303
2304void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002305 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002306 // Log the client rejected
2307 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002308 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002309}
2310
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002311void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
2312 // Log torch event
2313 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
2314 torchState, clientPid));
2315}
2316
Ruben Brunk6267b532015-04-30 17:44:07 -07002317void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
2318 const std::set<userid_t>& newUserIds) {
2319 String8 newUsers = toString(newUserIds);
2320 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002321 if (oldUsers.size() == 0) {
2322 oldUsers = "<None>";
2323 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07002324 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002325 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07002326 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002327}
2328
2329void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
2330 // Log the device removal
2331 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
2332}
2333
2334void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
2335 // Log the device removal
2336 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
2337}
2338
2339void CameraService::logClientDied(int clientPid, const char* reason) {
2340 // Log the device removal
2341 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07002342}
2343
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002344void CameraService::logServiceError(const char* msg, int errorCode) {
2345 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002346 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002347}
2348
Ruben Brunk36597b22015-03-20 22:15:57 -07002349status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
2350 uint32_t flags) {
2351
Mathias Agopian65ab4712010-07-14 17:59:35 -07002352 // Permission checks
2353 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002354 case SHELL_COMMAND_TRANSACTION: {
2355 int in = data.readFileDescriptor();
2356 int out = data.readFileDescriptor();
2357 int err = data.readFileDescriptor();
2358 int argc = data.readInt32();
2359 Vector<String16> args;
2360 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
2361 args.add(data.readString16());
2362 }
2363 sp<IBinder> unusedCallback;
2364 sp<IResultReceiver> resultReceiver;
2365 status_t status;
2366 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
2367 return status;
2368 }
2369 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
2370 return status;
2371 }
2372 status = shellCommand(in, out, err, args);
2373 if (resultReceiver != nullptr) {
2374 resultReceiver->send(status);
2375 }
2376 return NO_ERROR;
2377 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002378 }
2379
2380 return BnCameraService::onTransact(code, data, reply, flags);
2381}
2382
Mathias Agopian65ab4712010-07-14 17:59:35 -07002383// We share the media players for shutter and recording sound for all clients.
2384// A reference count is kept to determine when we will actually release the
2385// media players.
2386
Jaekyun Seokef498052018-03-23 13:09:44 +09002387sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
2388 sp<MediaPlayer> mp = new MediaPlayer();
2389 status_t error;
2390 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08002391 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09002392 error = mp->prepare();
2393 }
2394 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002395 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09002396 mp->disconnect();
2397 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002398 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002399 }
2400 return mp;
2401}
2402
username5755fea2018-12-27 09:48:08 +08002403void CameraService::increaseSoundRef() {
2404 Mutex::Autolock lock(mSoundLock);
2405 mSoundRef++;
2406}
2407
2408void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002409 ATRACE_CALL();
2410
username5755fea2018-12-27 09:48:08 +08002411 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
2412 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
2413 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
2414 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
2415 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2416 }
2417 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
2418 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
2419 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
2420 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002421 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08002422 }
2423 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
2424 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
2425 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
2426 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2427 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002428 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002429}
2430
username5755fea2018-12-27 09:48:08 +08002431void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002432 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002433 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002434 if (--mSoundRef) return;
2435
2436 for (int i = 0; i < NUM_SOUNDS; i++) {
2437 if (mSoundPlayer[i] != 0) {
2438 mSoundPlayer[i]->disconnect();
2439 mSoundPlayer[i].clear();
2440 }
2441 }
2442}
2443
2444void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002445 ATRACE_CALL();
2446
Mathias Agopian65ab4712010-07-14 17:59:35 -07002447 LOG1("playSound(%d)", kind);
2448 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002449 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002450 sp<MediaPlayer> player = mSoundPlayer[kind];
2451 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08002452 player->seekTo(0);
2453 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002454 }
2455}
2456
2457// ----------------------------------------------------------------------------
2458
2459CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002460 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002461 const String16& clientPackageName,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002462 const String8& cameraIdStr,
2463 int api1CameraId, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002464 int clientPid, uid_t clientUid,
2465 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002466 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08002467 IInterface::asBinder(cameraClient),
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002468 clientPackageName,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002469 cameraIdStr, cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002470 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002471 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002472 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08002473{
Jayant Chowdhary12361932018-08-27 14:46:13 -07002474 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002475 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002476
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002477 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002478
username5755fea2018-12-27 09:48:08 +08002479 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002480
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002481 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002482}
2483
Mathias Agopian65ab4712010-07-14 17:59:35 -07002484// tear down the client
2485CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002486 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08002487 mDestructionStarted = true;
2488
username5755fea2018-12-27 09:48:08 +08002489 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002490 // unconditionally disconnect. function is idempotent
2491 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002492}
2493
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002494sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
2495
Igor Murashkin634a5152013-02-20 17:15:11 -08002496CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002497 const sp<IBinder>& remoteCallback,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002498 const String16& clientPackageName,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002499 const String8& cameraIdStr, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002500 int clientPid, uid_t clientUid,
2501 int servicePid):
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002502 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing),
2503 mClientPackageName(clientPackageName), mClientPid(clientPid), mClientUid(clientUid),
2504 mServicePid(servicePid),
2505 mDisconnected(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002506 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002507 mRemoteBinder(remoteCallback)
Igor Murashkin634a5152013-02-20 17:15:11 -08002508{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002509 if (sCameraService == nullptr) {
2510 sCameraService = cameraService;
2511 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002512 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08002513 mDestructionStarted = false;
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08002514
2515 // In some cases the calling code has no access to the package it runs under.
2516 // For example, NDK camera API.
2517 // In this case we will get the packages for the calling UID and pick the first one
2518 // for attributing the app op. This will work correctly for runtime permissions
2519 // as for legacy apps we will toggle the app op for all packages in the UID.
2520 // The caveat is that the operation may be attributed to the wrong package and
2521 // stats based on app ops may be slightly off.
2522 if (mClientPackageName.size() <= 0) {
2523 sp<IServiceManager> sm = defaultServiceManager();
2524 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2525 if (binder == 0) {
2526 ALOGE("Cannot get permission service");
2527 // Leave mClientPackageName unchanged (empty) and the further interaction
2528 // with camera will fail in BasicClient::startCameraOps
2529 return;
2530 }
2531
2532 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2533 Vector<String16> packages;
2534
2535 permCtrl->getPackagesForUid(mClientUid, packages);
2536
2537 if (packages.isEmpty()) {
2538 ALOGE("No packages for calling UID");
2539 // Leave mClientPackageName unchanged (empty) and the further interaction
2540 // with camera will fail in BasicClient::startCameraOps
2541 return;
2542 }
2543 mClientPackageName = packages[0];
2544 }
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002545 if (!hardware::IPCThreadState::self()->isServingCall()) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002546 mAppOpsManager = std::make_unique<AppOpsManager>();
2547 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002548}
2549
2550CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002551 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08002552 mDestructionStarted = true;
2553}
2554
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002555binder::Status CameraService::BasicClient::disconnect() {
2556 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002557 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002558 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07002559 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002560 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002561
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002562 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002563 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07002564 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
2565 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002566
2567 sp<IBinder> remote = getRemote();
2568 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002569 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08002570 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002571
2572 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07002573 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002574 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
2575 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
2576 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002577
Igor Murashkincba2c162013-03-20 15:56:31 -07002578 // client shouldn't be able to call into us anymore
2579 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002580
2581 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08002582}
2583
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002584status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2585 // No dumping of clients directly over Binder,
2586 // must go through CameraService::dump
2587 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002588 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002589 return OK;
2590}
2591
Ruben Brunkcc776712015-02-17 20:18:47 -08002592String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002593 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08002594}
2595
2596
2597int CameraService::BasicClient::getClientPid() const {
2598 return mClientPid;
2599}
2600
Ruben Brunk6267b532015-04-30 17:44:07 -07002601uid_t CameraService::BasicClient::getClientUid() const {
2602 return mClientUid;
2603}
2604
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002605bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2606 // Defaults to API2.
2607 return level == API_2;
2608}
2609
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002610status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002611 {
2612 Mutex::Autolock l(mAudioRestrictionLock);
2613 mAudioRestriction = mode;
2614 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002615 sCameraService->updateAudioRestriction();
2616 return OK;
2617}
2618
2619int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002620 return sCameraService->updateAudioRestriction();
2621}
2622
2623int32_t CameraService::BasicClient::getAudioRestriction() const {
2624 Mutex::Autolock l(mAudioRestrictionLock);
2625 return mAudioRestriction;
2626}
2627
2628bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
2629 switch (mode) {
2630 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
2631 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
2632 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
2633 return true;
2634 default:
2635 return false;
2636 }
2637}
2638
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002639status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002640 ATRACE_CALL();
2641
Igor Murashkine6800ce2013-03-04 17:25:57 -08002642 {
2643 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002644 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002645 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002646 if (mAppOpsManager != nullptr) {
2647 // Notify app ops that the camera is not available
2648 mOpsCallback = new OpsCallback(this);
2649 int32_t res;
2650 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
2651 mClientPackageName, mOpsCallback);
2652 res = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA,
2653 mClientUid, mClientPackageName, /*startIfModeDefault*/ false);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002654
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002655 if (res == AppOpsManager::MODE_ERRORED) {
2656 ALOGI("Camera %s: Access for \"%s\" has been revoked",
2657 mCameraIdStr.string(), String8(mClientPackageName).string());
2658 return PERMISSION_DENIED;
2659 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002660
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002661 if (res == AppOpsManager::MODE_IGNORED) {
2662 ALOGI("Camera %s: Access for \"%s\" has been restricted",
2663 mCameraIdStr.string(), String8(mClientPackageName).string());
2664 // Return the same error as for device policy manager rejection
2665 return -EACCES;
2666 }
Svetoslav28e8ef72015-05-11 19:21:31 -07002667 }
2668
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002669 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002670
2671 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002672 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002673
Emilian Peev573291c2018-02-10 02:10:56 +00002674 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2675 if (canCastToApiClient(API_2)) {
2676 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2677 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002678 // Transition device state to OPEN
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002679 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
Emilian Peev573291c2018-02-10 02:10:56 +00002680 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002681
Emilian Peev53722fa2019-02-22 17:47:20 -08002682 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
2683
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002684 return OK;
2685}
2686
2687status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002688 ATRACE_CALL();
2689
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002690 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002691 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002692 // Notify app ops that the camera is available again
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002693 if (mAppOpsManager != nullptr) {
2694 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
2695 mClientPackageName);
2696 mOpsActive = false;
2697 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002698 // This function is called when a client disconnects. This should
2699 // release the camera, but actually only if it was in a proper
2700 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002701 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002702 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002703
Ruben Brunkcc776712015-02-17 20:18:47 -08002704 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002705 sCameraService->updateStatus(StatusInternal::PRESENT,
2706 mCameraIdStr, rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002707
Emilian Peev573291c2018-02-10 02:10:56 +00002708 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2709 if (canCastToApiClient(API_2)) {
2710 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2711 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002712 // Transition device state to CLOSED
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002713 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
Emilian Peev573291c2018-02-10 02:10:56 +00002714 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002715 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002716 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002717 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
2718 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002719 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002720 mOpsCallback.clear();
2721
Emilian Peev53722fa2019-02-22 17:47:20 -08002722 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
2723
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002724 return OK;
2725}
2726
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002727void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002728 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002729 if (mAppOpsManager == nullptr) {
2730 return;
2731 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002732 if (op != AppOpsManager::OP_CAMERA) {
2733 ALOGW("Unexpected app ops notification received: %d", op);
2734 return;
2735 }
2736
2737 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002738 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002739 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002740 ALOGV("checkOp returns: %d, %s ", res,
2741 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
2742 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
2743 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
2744 "UNKNOWN");
2745
2746 if (res != AppOpsManager::MODE_ALLOWED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002747 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002748 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08002749 block();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002750 }
2751}
2752
Svet Ganova453d0d2018-01-11 15:37:58 -08002753void CameraService::BasicClient::block() {
2754 ATRACE_CALL();
2755
2756 // Reset the client PID to allow server-initiated disconnect,
2757 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07002758 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08002759 CaptureResultExtras resultExtras; // a dummy result (invalid)
2760 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
2761 disconnect();
2762}
2763
Mathias Agopian65ab4712010-07-14 17:59:35 -07002764// ----------------------------------------------------------------------------
2765
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002766void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07002767 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002768 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07002769 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07002770 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
2771 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
2772 api1ErrorCode = CAMERA_ERROR_DISABLED;
2773 }
2774 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07002775 } else {
2776 ALOGE("mRemoteCallback is NULL!!");
2777 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002778}
2779
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002780// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002781binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002782 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002783 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08002784}
2785
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002786bool CameraService::Client::canCastToApiClient(apiLevel level) const {
2787 return level == API_1;
2788}
2789
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002790CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
2791 mClient(client) {
2792}
2793
2794void CameraService::Client::OpsCallback::opChanged(int32_t op,
2795 const String16& packageName) {
2796 sp<BasicClient> client = mClient.promote();
2797 if (client != NULL) {
2798 client->opChanged(op, packageName);
2799 }
2800}
2801
Mathias Agopian65ab4712010-07-14 17:59:35 -07002802// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08002803// UidPolicy
2804// ----------------------------------------------------------------------------
2805
2806void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002807 Mutex::Autolock _l(mUidLock);
2808
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002809 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07002810 status_t res = mAm.linkToDeath(this);
2811 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08002812 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08002813 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08002814 ActivityManager::PROCESS_STATE_UNKNOWN,
2815 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002816 if (res == OK) {
2817 mRegistered = true;
2818 ALOGV("UidPolicy: Registered with ActivityManager");
2819 }
Svet Ganova453d0d2018-01-11 15:37:58 -08002820}
2821
2822void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002823 Mutex::Autolock _l(mUidLock);
2824
Steven Moreland2f348142019-07-02 15:59:07 -07002825 mAm.unregisterUidObserver(this);
2826 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002827 mRegistered = false;
2828 mActiveUids.clear();
2829 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08002830}
2831
2832void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
2833 onUidIdle(uid, disabled);
2834}
2835
2836void CameraService::UidPolicy::onUidActive(uid_t uid) {
2837 Mutex::Autolock _l(mUidLock);
2838 mActiveUids.insert(uid);
2839}
2840
2841void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
2842 bool deleted = false;
2843 {
2844 Mutex::Autolock _l(mUidLock);
2845 if (mActiveUids.erase(uid) > 0) {
2846 deleted = true;
2847 }
2848 }
2849 if (deleted) {
2850 sp<CameraService> service = mService.promote();
2851 if (service != nullptr) {
2852 service->blockClientsForUid(uid);
2853 }
2854 }
2855}
2856
Emilian Peev53722fa2019-02-22 17:47:20 -08002857void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
2858 int64_t /*procStateSeq*/) {
2859 bool procStateChange = false;
2860 {
2861 Mutex::Autolock _l(mUidLock);
2862 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
2863 (mMonitoredUids[uid].first != procState)) {
2864 mMonitoredUids[uid].first = procState;
2865 procStateChange = true;
2866 }
2867 }
2868
2869 if (procStateChange) {
2870 sp<CameraService> service = mService.promote();
2871 if (service != nullptr) {
2872 service->notifyMonitoredUids();
2873 }
2874 }
2875}
2876
2877void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
2878 Mutex::Autolock _l(mUidLock);
2879 auto it = mMonitoredUids.find(uid);
2880 if (it != mMonitoredUids.end()) {
2881 it->second.second++;
2882 } else {
2883 mMonitoredUids.emplace(
2884 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
2885 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
2886 }
2887}
2888
2889void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
2890 Mutex::Autolock _l(mUidLock);
2891 auto it = mMonitoredUids.find(uid);
2892 if (it != mMonitoredUids.end()) {
2893 it->second.second--;
2894 if (it->second.second == 0) {
2895 mMonitoredUids.erase(it);
2896 }
2897 } else {
2898 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
2899 }
2900}
2901
Svet Ganov7b4ab782018-03-25 12:48:10 -07002902bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002903 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07002904 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08002905}
2906
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07002907static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
2908static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07002909
Svet Ganov7b4ab782018-03-25 12:48:10 -07002910bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002911 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002912 // If activity manager is unreachable, assume everything is active
2913 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002914 return true;
2915 }
2916 auto it = mOverrideUids.find(uid);
2917 if (it != mOverrideUids.end()) {
2918 return it->second;
2919 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07002920 bool active = mActiveUids.find(uid) != mActiveUids.end();
2921 if (!active) {
2922 // We want active UIDs to always access camera with their first attempt since
2923 // there is no guarantee the app is robustly written and would retry getting
2924 // the camera on failure. The inverse case is not a problem as we would take
2925 // camera away soon once we get the callback that the uid is no longer active.
2926 ActivityManager am;
2927 // Okay to access with a lock held as UID changes are dispatched without
2928 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07002929 int64_t startTimeMillis = 0;
2930 do {
2931 // TODO: Fix this b/109950150!
2932 // Okay this is a hack. There is a race between the UID turning active and
2933 // activity being resumed. The proper fix is very risky, so we temporary add
2934 // some polling which should happen pretty rarely anyway as the race is hard
2935 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07002936 active = mActiveUids.find(uid) != mActiveUids.end();
2937 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07002938 if (active) {
2939 break;
2940 }
2941 if (startTimeMillis <= 0) {
2942 startTimeMillis = uptimeMillis();
2943 }
2944 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07002945 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07002946 if (remainingTimeMillis <= 0) {
2947 break;
2948 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07002949 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
2950
2951 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07002952 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07002953 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07002954 } while (true);
2955
Svet Ganov7b4ab782018-03-25 12:48:10 -07002956 if (active) {
2957 // Now that we found out the UID is actually active, cache that
2958 mActiveUids.insert(uid);
2959 }
2960 }
2961 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08002962}
2963
Varun Shahb42f1eb2019-04-16 14:45:13 -07002964int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
2965 Mutex::Autolock _l(mUidLock);
2966 return getProcStateLocked(uid);
2967}
2968
2969int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
2970 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
2971 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
2972 procState = mMonitoredUids[uid].first;
2973 }
2974 return procState;
2975}
2976
Svet Ganov7b4ab782018-03-25 12:48:10 -07002977void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
2978 String16 callingPackage, bool active) {
2979 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08002980}
2981
Svet Ganov7b4ab782018-03-25 12:48:10 -07002982void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
2983 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08002984}
2985
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002986void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
2987 Mutex::Autolock _l(mUidLock);
2988 ALOGV("UidPolicy: ActivityManager has died");
2989 mRegistered = false;
2990 mActiveUids.clear();
2991}
2992
Svet Ganov7b4ab782018-03-25 12:48:10 -07002993void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
2994 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002995 bool wasActive = false;
2996 bool isActive = false;
2997 {
2998 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07002999 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003000 mOverrideUids.erase(uid);
3001 if (insert) {
3002 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3003 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003004 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003005 }
3006 if (wasActive != isActive && !isActive) {
3007 sp<CameraService> service = mService.promote();
3008 if (service != nullptr) {
3009 service->blockClientsForUid(uid);
3010 }
3011 }
3012}
3013
3014// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08003015// SensorPrivacyPolicy
3016// ----------------------------------------------------------------------------
3017void CameraService::SensorPrivacyPolicy::registerSelf() {
3018 Mutex::Autolock _l(mSensorPrivacyLock);
3019 if (mRegistered) {
3020 return;
3021 }
3022 SensorPrivacyManager spm;
3023 spm.addSensorPrivacyListener(this);
3024 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
3025 status_t res = spm.linkToDeath(this);
3026 if (res == OK) {
3027 mRegistered = true;
3028 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3029 }
3030}
3031
3032void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3033 Mutex::Autolock _l(mSensorPrivacyLock);
3034 SensorPrivacyManager spm;
3035 spm.removeSensorPrivacyListener(this);
3036 spm.unlinkToDeath(this);
3037 mRegistered = false;
3038 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3039}
3040
3041bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3042 Mutex::Autolock _l(mSensorPrivacyLock);
3043 return mSensorPrivacyEnabled;
3044}
3045
3046binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3047 {
3048 Mutex::Autolock _l(mSensorPrivacyLock);
3049 mSensorPrivacyEnabled = enabled;
3050 }
3051 // if sensor privacy is enabled then block all clients from accessing the camera
3052 if (enabled) {
3053 sp<CameraService> service = mService.promote();
3054 if (service != nullptr) {
3055 service->blockAllClients();
3056 }
3057 }
3058 return binder::Status::ok();
3059}
3060
3061void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3062 Mutex::Autolock _l(mSensorPrivacyLock);
3063 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3064 mRegistered = false;
3065}
3066
3067// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003068// CameraState
3069// ----------------------------------------------------------------------------
3070
3071CameraService::CameraState::CameraState(const String8& id, int cost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003072 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind) : mId(id),
3073 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
3074 mSystemCameraKind(systemCameraKind) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003075
3076CameraService::CameraState::~CameraState() {}
3077
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003078CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003079 Mutex::Autolock lock(mStatusLock);
3080 return mStatus;
3081}
3082
3083CameraParameters CameraService::CameraState::getShimParams() const {
3084 return mShimParams;
3085}
3086
3087void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3088 mShimParams = params;
3089}
3090
3091int CameraService::CameraState::getCost() const {
3092 return mCost;
3093}
3094
3095std::set<String8> CameraService::CameraState::getConflicting() const {
3096 return mConflicting;
3097}
3098
3099String8 CameraService::CameraState::getId() const {
3100 return mId;
3101}
3102
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003103SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3104 return mSystemCameraKind;
3105}
3106
Ruben Brunkcc776712015-02-17 20:18:47 -08003107// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07003108// ClientEventListener
3109// ----------------------------------------------------------------------------
3110
3111void CameraService::ClientEventListener::onClientAdded(
3112 const resource_policy::ClientDescriptor<String8,
3113 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003114 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003115 if (basicClient.get() != nullptr) {
3116 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3117 notifier.noteStartCamera(descriptor.getKey(),
3118 static_cast<int>(basicClient->getClientUid()));
3119 }
3120}
3121
3122void CameraService::ClientEventListener::onClientRemoved(
3123 const resource_policy::ClientDescriptor<String8,
3124 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003125 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003126 if (basicClient.get() != nullptr) {
3127 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3128 notifier.noteStopCamera(descriptor.getKey(),
3129 static_cast<int>(basicClient->getClientUid()));
3130 }
3131}
3132
3133
3134// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003135// CameraClientManager
3136// ----------------------------------------------------------------------------
3137
Ruben Brunk99e69712015-05-26 17:25:07 -07003138CameraService::CameraClientManager::CameraClientManager() {
3139 setListener(std::make_shared<ClientEventListener>());
3140}
3141
Ruben Brunkcc776712015-02-17 20:18:47 -08003142CameraService::CameraClientManager::~CameraClientManager() {}
3143
3144sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
3145 const String8& id) const {
3146 auto descriptor = get(id);
3147 if (descriptor == nullptr) {
3148 return sp<BasicClient>{nullptr};
3149 }
3150 return descriptor->getValue();
3151}
3152
3153String8 CameraService::CameraClientManager::toString() const {
3154 auto all = getAll();
3155 String8 ret("[");
3156 bool hasAny = false;
3157 for (auto& i : all) {
3158 hasAny = true;
3159 String8 key = i->getKey();
3160 int32_t cost = i->getCost();
3161 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00003162 int32_t score = i->getPriority().getScore();
3163 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08003164 auto conflicting = i->getConflicting();
3165 auto clientSp = i->getValue();
3166 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07003167 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08003168 if (clientSp.get() != nullptr) {
3169 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07003170 uid_t clientUid = clientSp->getClientUid();
3171 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003172 }
Emilian Peev8131a262017-02-01 12:33:43 +00003173 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
3174 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08003175
Ruben Brunk6267b532015-04-30 17:44:07 -07003176 if (clientSp.get() != nullptr) {
3177 ret.appendFormat("User Id: %d, ", clientUserId);
3178 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003179 if (packageName.size() != 0) {
3180 ret.appendFormat("Client Package Name: %s", packageName.string());
3181 }
3182
3183 ret.append(", Conflicting Client Devices: {");
3184 for (auto& j : conflicting) {
3185 ret.appendFormat("%s, ", j.string());
3186 }
3187 ret.append("})");
3188 }
3189 if (hasAny) ret.append("\n");
3190 ret.append("]\n");
3191 return ret;
3192}
3193
3194CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3195 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00003196 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
3197 int32_t state) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003198
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003199 bool isVendorClient = hardware::IPCThreadState::self()->isServingCall();
3200 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
3201 int32_t state_adj = isVendorClient ? kVendorClientState: state;
3202
Ruben Brunkcc776712015-02-17 20:18:47 -08003203 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003204 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08003205}
3206
3207CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3208 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
3209 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00003210 partial->getConflicting(), partial->getPriority().getScore(),
3211 partial->getOwnerId(), partial->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08003212}
3213
3214// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07003215
3216static const int kDumpLockRetries = 50;
3217static const int kDumpLockSleep = 60000;
3218
3219static bool tryLock(Mutex& mutex)
3220{
3221 bool locked = false;
3222 for (int i = 0; i < kDumpLockRetries; ++i) {
3223 if (mutex.tryLock() == NO_ERROR) {
3224 locked = true;
3225 break;
3226 }
3227 usleep(kDumpLockSleep);
3228 }
3229 return locked;
3230}
3231
3232status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003233 ATRACE_CALL();
3234
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003235 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003236 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003237 CameraThreadState::getCallingPid(),
3238 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003239 return NO_ERROR;
3240 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003241 bool locked = tryLock(mServiceLock);
3242 // failed to lock - CameraService is probably deadlocked
3243 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003244 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003245 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003246
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003247 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003248 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07003249
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003250 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003251 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08003252
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003253 if (locked) mServiceLock.unlock();
3254 return NO_ERROR;
3255 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003256 dprintf(fd, "\n== Service global info: ==\n\n");
3257 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003258 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07003259 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
3260 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003261 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
3262 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
3263 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003264 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003265 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
3266 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003267
3268 dumpEventLog(fd);
3269
3270 bool stateLocked = tryLock(mCameraStatesLock);
3271 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003272 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003273 }
3274
Emilian Peevbd8c5032018-02-14 23:05:40 +00003275 int argSize = args.size();
3276 for (int i = 0; i < argSize; i++) {
3277 if (args[i] == TagMonitor::kMonitorOption) {
3278 if (i + 1 < argSize) {
3279 mMonitorTags = String8(args[i + 1]);
3280 }
3281 break;
3282 }
3283 }
3284
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003285 for (auto& state : mCameraStates) {
3286 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003287
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003288 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003289
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003290 CameraParameters p = state.second->getShimParams();
3291 if (!p.isEmpty()) {
3292 dprintf(fd, " Camera1 API shim is using parameters:\n ");
3293 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003294 }
3295
3296 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08003297 if (clientDescriptor != nullptr) {
3298 dprintf(fd, " Device %s is open. Client instance dump:\n",
3299 cameraId.string());
3300 dprintf(fd, " Client priority score: %d state: %d\n",
3301 clientDescriptor->getPriority().getScore(),
3302 clientDescriptor->getPriority().getState());
3303 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
3304
3305 auto client = clientDescriptor->getValue();
3306 dprintf(fd, " Client package: %s\n",
3307 String8(client->getPackageName()).string());
3308
3309 client->dumpClient(fd, args);
3310 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003311 dprintf(fd, " Device %s is closed, no client instance\n",
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003312 cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003313 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003314
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003315 }
3316
3317 if (stateLocked) mCameraStatesLock.unlock();
3318
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003319 if (locked) mServiceLock.unlock();
3320
Emilian Peevf53f66e2017-04-11 14:29:43 +01003321 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003322
3323 dprintf(fd, "\n== Vendor tags: ==\n\n");
3324
3325 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
3326 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00003327 sp<VendorTagDescriptorCache> cache =
3328 VendorTagDescriptorCache::getGlobalVendorTagCache();
3329 if (cache == NULL) {
3330 dprintf(fd, "No vendor tags.\n");
3331 } else {
3332 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
3333 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003334 } else {
3335 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
3336 }
3337
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003338 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003339 dprintf(fd, "\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003340 camera3::CameraTraces::dump(fd, args);
3341
3342 // Process dump arguments, if any
3343 int n = args.size();
3344 String16 verboseOption("-v");
3345 String16 unreachableOption("--unreachable");
3346 for (int i = 0; i < n; i++) {
3347 if (args[i] == verboseOption) {
3348 // change logging level
3349 if (i + 1 >= n) continue;
3350 String8 levelStr(args[i+1]);
3351 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003352 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003353 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003354 } else if (args[i] == unreachableOption) {
3355 // Dump memory analysis
3356 // TODO - should limit be an argument parameter?
3357 UnreachableMemoryInfo info;
3358 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
3359 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003360 dprintf(fd, "\n== Unable to dump unreachable memory. "
3361 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003362 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003363 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003364 std::string s = info.ToString(/*log_contents*/ true);
3365 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003366 }
3367 }
3368 }
3369 return NO_ERROR;
3370}
3371
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003372void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003373 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003374
3375 Mutex::Autolock l(mLogLock);
3376 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003377 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003378 }
3379
3380 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003381 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003382 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003383 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003384 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003385 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003386}
3387
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003388void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003389 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003390 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
3391 if (mTorchClientMap[i] == who) {
3392 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003393 String8 cameraId = mTorchClientMap.keyAt(i);
3394 status_t res = mFlashlight->setTorchMode(cameraId, false);
3395 if (res) {
3396 ALOGE("%s: torch client died but couldn't turn off torch: "
3397 "%s (%d)", __FUNCTION__, strerror(-res), res);
3398 return;
3399 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003400 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003401 break;
3402 }
3403 }
3404}
3405
Ruben Brunkcc776712015-02-17 20:18:47 -08003406/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003407
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003408 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07003409 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
3410 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003411 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003412 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003413 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003414
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003415 // check torch client
3416 handleTorchClientBinderDied(who);
3417
3418 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08003419 if(!evictClientIdByRemote(who)) {
3420 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003421 return;
3422 }
3423
Ruben Brunkcc776712015-02-17 20:18:47 -08003424 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
3425 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003426}
3427
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003428void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003429 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08003430}
3431
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003432void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
3433 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003434 // Do not lock mServiceLock here or can get into a deadlock from
3435 // connect() -> disconnect -> updateStatus
3436
3437 auto state = getCameraState(cameraId);
3438
3439 if (state == nullptr) {
3440 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
3441 cameraId.string());
3442 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07003443 }
3444
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003445 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
3446 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3447 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3448 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
3449 return;
3450 }
3451
Ruben Brunkcc776712015-02-17 20:18:47 -08003452 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
3453 // of the listeners with both the mStatusStatus and mStatusListenerLock held
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003454 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003455 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003456
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003457 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003458 // Update torch status if it has a flash unit.
3459 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003460 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003461 if (getTorchStatusLocked(cameraId, &torchStatus) !=
3462 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003463 TorchModeStatus newTorchStatus =
3464 status == StatusInternal::PRESENT ?
3465 TorchModeStatus::AVAILABLE_OFF :
3466 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003467 if (torchStatus != newTorchStatus) {
3468 onTorchStatusChangedLocked(cameraId, newTorchStatus);
3469 }
3470 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003471 }
3472
3473 Mutex::Autolock lock(mStatusListenerLock);
3474
3475 for (auto& listener : mListenerList) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003476 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003477 listener->getListenerPid(), listener->getListenerUid())) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003478 ALOGV("Skipping camera discovery callback for system-only camera %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003479 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003480 continue;
3481 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003482 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08003483 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08003484 }
3485 });
Igor Murashkincba2c162013-03-20 15:56:31 -07003486}
3487
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003488template<class Func>
3489void CameraService::CameraState::updateStatus(StatusInternal status,
3490 const String8& cameraId,
3491 std::initializer_list<StatusInternal> rejectSourceStates,
3492 Func onStatusUpdatedLocked) {
3493 Mutex::Autolock lock(mStatusLock);
3494 StatusInternal oldStatus = mStatus;
3495 mStatus = status;
3496
3497 if (oldStatus == status) {
3498 return;
3499 }
3500
3501 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
3502 cameraId.string(), oldStatus, status);
3503
3504 if (oldStatus == StatusInternal::NOT_PRESENT &&
3505 (status != StatusInternal::PRESENT &&
3506 status != StatusInternal::ENUMERATING)) {
3507
3508 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
3509 __FUNCTION__);
3510 mStatus = oldStatus;
3511 return;
3512 }
3513
3514 /**
3515 * Sometimes we want to conditionally do a transition.
3516 * For example if a client disconnects, we want to go to PRESENT
3517 * only if we weren't already in NOT_PRESENT or ENUMERATING.
3518 */
3519 for (auto& rejectStatus : rejectSourceStates) {
3520 if (oldStatus == rejectStatus) {
3521 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
3522 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
3523 mStatus = oldStatus;
3524 return;
3525 }
3526 }
3527
3528 onStatusUpdatedLocked(cameraId, status);
3529}
3530
Eino-Ville Talvalae8c96c72017-06-27 12:24:07 -07003531void CameraService::updateProxyDeviceState(int newState,
Emilian Peev573291c2018-02-10 02:10:56 +00003532 const String8& cameraId, int facing, const String16& clientName, int apiLevel) {
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003533 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
3534 if (proxyBinder == nullptr) return;
3535 String16 id(cameraId);
Emilian Peev573291c2018-02-10 02:10:56 +00003536 proxyBinder->notifyCameraState(id, newState, facing, clientName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003537}
3538
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003539status_t CameraService::getTorchStatusLocked(
3540 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003541 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003542 if (!status) {
3543 return BAD_VALUE;
3544 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003545 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3546 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003547 // invalid camera ID or the camera doesn't have a flash unit
3548 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003549 }
3550
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003551 *status = mTorchStatusMap.valueAt(index);
3552 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003553}
3554
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003555status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003556 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003557 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3558 if (index == NAME_NOT_FOUND) {
3559 return BAD_VALUE;
3560 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003561 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003562
3563 return OK;
3564}
3565
Svet Ganova453d0d2018-01-11 15:37:58 -08003566void CameraService::blockClientsForUid(uid_t uid) {
3567 const auto clients = mActiveClientManager.getAll();
3568 for (auto& current : clients) {
3569 if (current != nullptr) {
3570 const auto basicClient = current->getValue();
3571 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
3572 basicClient->block();
3573 }
3574 }
3575 }
3576}
3577
Michael Grooverd1d435a2018-12-18 17:39:42 -08003578void CameraService::blockAllClients() {
3579 const auto clients = mActiveClientManager.getAll();
3580 for (auto& current : clients) {
3581 if (current != nullptr) {
3582 const auto basicClient = current->getValue();
3583 if (basicClient.get() != nullptr) {
3584 basicClient->block();
3585 }
3586 }
3587 }
3588}
3589
Svet Ganova453d0d2018-01-11 15:37:58 -08003590// NOTE: This is a remote API - make sure all args are validated
3591status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
3592 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
3593 return PERMISSION_DENIED;
3594 }
3595 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
3596 return BAD_VALUE;
3597 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003598 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003599 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003600 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003601 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003602 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003603 return handleGetUidState(args, out, err);
3604 } else if (args.size() == 1 && args[0] == String16("help")) {
3605 printHelp(out);
3606 return NO_ERROR;
3607 }
3608 printHelp(err);
3609 return BAD_VALUE;
3610}
3611
3612status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003613 String16 packageName = args[1];
3614
Svet Ganova453d0d2018-01-11 15:37:58 -08003615 bool active = false;
3616 if (args[2] == String16("active")) {
3617 active = true;
3618 } else if ((args[2] != String16("idle"))) {
3619 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
3620 return BAD_VALUE;
3621 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003622
3623 int userId = 0;
3624 if (args.size() >= 5 && args[3] == String16("--user")) {
3625 userId = atoi(String8(args[4]));
3626 }
3627
3628 uid_t uid;
3629 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
3630 return BAD_VALUE;
3631 }
3632
3633 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08003634 return NO_ERROR;
3635}
3636
3637status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003638 String16 packageName = args[1];
3639
3640 int userId = 0;
3641 if (args.size() >= 4 && args[2] == String16("--user")) {
3642 userId = atoi(String8(args[3]));
3643 }
3644
3645 uid_t uid;
3646 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003647 return BAD_VALUE;
3648 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003649
3650 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08003651 return NO_ERROR;
3652}
3653
3654status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003655 String16 packageName = args[1];
3656
3657 int userId = 0;
3658 if (args.size() >= 4 && args[2] == String16("--user")) {
3659 userId = atoi(String8(args[3]));
3660 }
3661
3662 uid_t uid;
3663 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003664 return BAD_VALUE;
3665 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003666
3667 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003668 return dprintf(out, "active\n");
3669 } else {
3670 return dprintf(out, "idle\n");
3671 }
3672}
3673
3674status_t CameraService::printHelp(int out) {
3675 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07003676 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
3677 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
3678 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08003679 " help print this message\n");
3680}
3681
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003682int32_t CameraService::updateAudioRestriction() {
3683 Mutex::Autolock lock(mServiceLock);
3684 return updateAudioRestrictionLocked();
3685}
3686
3687int32_t CameraService::updateAudioRestrictionLocked() {
3688 int32_t mode = 0;
3689 // iterate through all active client
3690 for (const auto& i : mActiveClientManager.getAll()) {
3691 const auto clientSp = i->getValue();
3692 mode |= clientSp->getAudioRestriction();
3693 }
3694
3695 bool modeChanged = (mAudioRestriction != mode);
3696 mAudioRestriction = mode;
3697 if (modeChanged) {
3698 mAppOps.setCameraAudioRestriction(mode);
3699 }
3700 return mode;
3701}
3702
Mathias Agopian65ab4712010-07-14 17:59:35 -07003703}; // namespace android