blob: 2fe717939b26d163920afdd47b63ed8cadef86d9 [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;
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800131const String8 CameraService::kOfflineDevice("offline-");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700132
Eino-Ville Talvala7d5569f2019-04-08 13:57:54 -0700133Mutex CameraService::sProxyMutex;
134sp<hardware::ICameraServiceProxy> CameraService::sCameraServiceProxy;
135
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800136CameraService::CameraService() :
137 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800138 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700139 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700140 mSoundRef(0), mInitialized(false),
141 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000142 ALOGI("CameraService started (pid=%d)", getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800143 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700144}
145
Iliyan Malchev8951a972011-04-14 16:55:59 -0700146void CameraService::onFirstRef()
147{
Ruben Brunkcc776712015-02-17 20:18:47 -0800148 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800149
Iliyan Malchev8951a972011-04-14 16:55:59 -0700150 BnCameraService::onFirstRef();
151
Ruben Brunk99e69712015-05-26 17:25:07 -0700152 // Update battery life tracking if service is restarting
153 BatteryNotifier& notifier(BatteryNotifier::getInstance());
154 notifier.noteResetCamera();
155 notifier.noteResetFlashlight();
156
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800157 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800158
Emilian Peevf53f66e2017-04-11 14:29:43 +0100159 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800160 if (res == OK) {
161 mInitialized = true;
162 }
163
Svet Ganova453d0d2018-01-11 15:37:58 -0800164 mUidPolicy = new UidPolicy(this);
165 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800166 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
167 mSensorPrivacyPolicy->registerSelf();
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700168 mAppOps.setCameraAudioRestriction(mAudioRestriction);
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700169 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
170 if (hcs->registerAsService() != android::OK) {
171 ALOGE("%s: Failed to register default android.frameworks.cameraservice.service@1.0",
172 __FUNCTION__);
173 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700174
175 // This needs to be last call in this function, so that it's as close to
176 // ServiceManager::addService() as possible.
177 CameraService::pingCameraServiceProxy();
178 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800179}
180
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800181status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800182 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100183
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800184 std::vector<std::string> deviceIds;
185 {
186 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800187
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800188 if (nullptr == mCameraProviderManager.get()) {
189 mCameraProviderManager = new CameraProviderManager();
190 res = mCameraProviderManager->initialize(this);
191 if (res != OK) {
192 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
193 __FUNCTION__, strerror(-res), res);
194 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100195 }
196 }
197
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800198
199 // Setup vendor tags before we call get_camera_info the first time
200 // because HAL might need to setup static vendor keys in get_camera_info
201 // TODO: maybe put this into CameraProviderManager::initialize()?
202 mCameraProviderManager->setUpVendorTags();
203
204 if (nullptr == mFlashlight.get()) {
205 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700206 }
207
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800208 res = mFlashlight->findFlashUnits();
209 if (res != OK) {
210 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
211 }
212
213 deviceIds = mCameraProviderManager->getCameraDeviceIds();
214 }
215
216
217 for (auto& cameraId : deviceIds) {
218 String8 id8 = String8(cameraId.c_str());
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800219 if (getCameraState(id8) == nullptr) {
220 onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
221 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800222 }
223
224 return OK;
225}
226
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700227sp<ICameraServiceProxy> CameraService::getCameraServiceProxy() {
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800228#ifndef __BRILLO__
Eino-Ville Talvala7d5569f2019-04-08 13:57:54 -0700229 Mutex::Autolock al(sProxyMutex);
230 if (sCameraServiceProxy == nullptr) {
231 sp<IServiceManager> sm = defaultServiceManager();
232 // Use checkService because cameraserver normally starts before the
233 // system server and the proxy service. So the long timeout that getService
234 // has before giving up is inappropriate.
235 sp<IBinder> binder = sm->checkService(String16("media.camera.proxy"));
236 if (binder != nullptr) {
237 sCameraServiceProxy = interface_cast<ICameraServiceProxy>(binder);
238 }
Ruben Brunk2823ce02015-05-19 17:25:13 -0700239 }
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800240#endif
Eino-Ville Talvala7d5569f2019-04-08 13:57:54 -0700241 return sCameraServiceProxy;
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700242}
243
244void CameraService::pingCameraServiceProxy() {
245 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
246 if (proxyBinder == nullptr) return;
Ruben Brunk2823ce02015-05-19 17:25:13 -0700247 proxyBinder->pingForUserUpdate();
Iliyan Malchev8951a972011-04-14 16:55:59 -0700248}
249
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800250void CameraService::broadcastTorchModeStatus(const String8& cameraId, TorchModeStatus status) {
251 Mutex::Autolock lock(mStatusListenerLock);
252
253 for (auto& i : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700254 i->getListener()->onTorchStatusChanged(mapToInterface(status), String16{cameraId});
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800255 }
256}
257
Mathias Agopian65ab4712010-07-14 17:59:35 -0700258CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800259 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800260 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800261 mSensorPrivacyPolicy->unregisterSelf();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700262}
263
Emilian Peevaee727d2017-05-04 16:35:48 +0100264void CameraService::onNewProviderRegistered() {
265 enumerateProviders();
266}
267
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700268void CameraService::filterAPI1SystemCameraLocked(
269 const std::vector<std::string> &normalDeviceIds) {
270 mNormalDeviceIdsWithoutSystemCamera.clear();
271 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700272 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
273 if (getSystemCameraKind(String8(deviceId.c_str()), &deviceKind) != OK) {
274 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
275 continue;
276 }
277 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700278 // All system camera ids will necessarily come after public camera
279 // device ids as per the HAL interface contract.
280 break;
281 }
282 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
283 }
284 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
285 mNormalDeviceIdsWithoutSystemCamera.size());
286}
287
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700288status_t CameraService::getSystemCameraKind(const String8& cameraId, SystemCameraKind *kind) const {
289 auto state = getCameraState(cameraId);
290 if (state != nullptr) {
291 *kind = state->getSystemCameraKind();
292 return OK;
293 }
294 // Hidden physical camera ids won't have CameraState
295 return mCameraProviderManager->getSystemCameraKind(cameraId.c_str(), kind);
296}
297
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800298void CameraService::updateCameraNumAndIds() {
299 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700300 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
301 // Excludes hidden secure cameras
302 mNumberOfCameras =
303 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
304 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800305 mNormalDeviceIds =
306 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700307 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800308}
309
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100310void CameraService::addStates(const String8 id) {
311 std::string cameraId(id.c_str());
312 hardware::camera::common::V1_0::CameraResourceCost cost;
313 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700314 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100315 if (res != OK) {
316 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
317 return;
318 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700319 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
320 if (res != OK) {
321 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
322 return;
323 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100324 std::set<String8> conflicting;
325 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
326 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
327 }
328
329 {
330 Mutex::Autolock lock(mCameraStatesLock);
331 mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700332 conflicting, deviceKind));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100333 }
334
335 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100336 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100337 mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800338
339 broadcastTorchModeStatus(id, TorchModeStatus::AVAILABLE_OFF);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100340 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800341
342 updateCameraNumAndIds();
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100343 logDeviceAdded(id, "Device added");
344}
345
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100346void CameraService::removeStates(const String8 id) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800347 updateCameraNumAndIds();
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100348 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100349 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100350 mTorchStatusMap.removeItem(id);
351 }
352
353 {
354 Mutex::Autolock lock(mCameraStatesLock);
355 mCameraStates.erase(id);
356 }
357}
358
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800359void CameraService::onDeviceStatusChanged(const String8& id,
360 CameraDeviceStatus newHalStatus) {
361 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
362 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700363
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800364 StatusInternal newStatus = mapToInternal(newHalStatus);
365
Ruben Brunkcc776712015-02-17 20:18:47 -0800366 std::shared_ptr<CameraState> state = getCameraState(id);
367
368 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700369 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100370 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700371 __FUNCTION__, id.string());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100372
373 // First add as absent to make sure clients are notified below
374 addStates(id);
375
376 updateStatus(newStatus, id);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700377 } else {
378 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
379 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700380 return;
381 }
382
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800383 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800384
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800385 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800386 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700387 return;
388 }
389
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800390 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700391 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
392 newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800393
394 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
395 // to this device until the status changes
396 updateStatus(StatusInternal::NOT_PRESENT, id);
397
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800398 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700399 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800400 // Don't do this in updateStatus to avoid deadlock over mServiceLock
401 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700402
Ruben Brunkcc776712015-02-17 20:18:47 -0800403 // Remove cached shim parameters
404 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700405
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800406 // Remove online as well as offline client from the list of active clients,
407 // if they are present
408 clientToDisconnectOnline = removeClientLocked(id);
409 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700410 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800411
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800412 disconnectClient(id, clientToDisconnectOnline);
413 disconnectClient(kOfflineDevice + id, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700414
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100415 removeStates(id);
Ruben Brunkcc776712015-02-17 20:18:47 -0800416 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800417 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700418 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
419 newStatus));
420 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800421 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700422 }
423
Igor Murashkincba2c162013-03-20 15:56:31 -0700424}
425
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800426void CameraService::disconnectClient(const String8& id, sp<BasicClient> clientToDisconnect) {
427 if (clientToDisconnect.get() != nullptr) {
428 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
429 __FUNCTION__, id.string());
430 // Notify the client of disconnection
431 clientToDisconnect->notifyError(
432 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
433 CaptureResultExtras{});
434 // Ensure not in binder RPC so client disconnect PID checks work correctly
435 LOG_ALWAYS_FATAL_IF(CameraThreadState::getCallingPid() != getpid(),
436 "onDeviceStatusChanged must be called from the camera service process!");
437 clientToDisconnect->disconnect();
438 }
439}
440
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800441void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800442 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800443 Mutex::Autolock al(mTorchStatusMutex);
444 onTorchStatusChangedLocked(cameraId, newStatus);
445}
446
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800447void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800448 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800449 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
450 __FUNCTION__, cameraId.string(), newStatus);
451
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800452 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800453 status_t res = getTorchStatusLocked(cameraId, &status);
454 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700455 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
456 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800457 return;
458 }
459 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800460 return;
461 }
462
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800463 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800464 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800465 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
466 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800467 return;
468 }
469
Ruben Brunkcc776712015-02-17 20:18:47 -0800470 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700471 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700472 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700473 auto iter = mTorchUidMap.find(cameraId);
474 if (iter != mTorchUidMap.end()) {
475 int oldUid = iter->second.second;
476 int newUid = iter->second.first;
477 BatteryNotifier& notifier(BatteryNotifier::getInstance());
478 if (oldUid != newUid) {
479 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800480 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700481 notifier.noteFlashlightOff(cameraId, oldUid);
482 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800483 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700484 notifier.noteFlashlightOn(cameraId, newUid);
485 }
486 iter->second.second = newUid;
487 } else {
488 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800489 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700490 notifier.noteFlashlightOn(cameraId, oldUid);
491 } else {
492 notifier.noteFlashlightOff(cameraId, oldUid);
493 }
494 }
495 }
496 }
497
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800498 broadcastTorchModeStatus(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800499}
500
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700501static bool hasPermissionsForSystemCamera(int callingPid, int callingUid) {
502 return checkPermission(sSystemCameraPermission, callingPid, callingUid) &&
503 checkPermission(sCameraPermission, callingPid, callingUid);
504}
505
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800506Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700507 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100508 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700509 bool hasSystemCameraPermissions =
510 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
511 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700512 switch (type) {
513 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700514 if (hasSystemCameraPermissions) {
515 *numCameras = static_cast<int>(mNormalDeviceIds.size());
516 } else {
517 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
518 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800519 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700520 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700521 if (hasSystemCameraPermissions) {
522 *numCameras = mNumberOfCameras;
523 } else {
524 *numCameras = mNumberOfCamerasWithoutSystemCamera;
525 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800526 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700527 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800528 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700529 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800530 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
531 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700532 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800533 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700534}
535
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800536Status CameraService::getCameraInfo(int cameraId,
537 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700538 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100539 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700540 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
541 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
542 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
543 "characteristics for system only device %s: ", cameraIdStr.c_str());
544 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100545
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800546 if (!mInitialized) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800547 return STATUS_ERROR(ERROR_DISCONNECTED,
548 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700549 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700550 bool hasSystemCameraPermissions =
551 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
552 CameraThreadState::getCallingUid());
553 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
554 if (hasSystemCameraPermissions) {
555 cameraIdBound = mNumberOfCameras;
556 }
557 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800558 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
559 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700560 }
561
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800562 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800563 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700564 cameraIdStr.c_str(), cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100565 if (err != OK) {
566 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
567 "Error retrieving camera info from device %d: %s (%d)", cameraId,
568 strerror(-err), err);
Ruben Brunkcc776712015-02-17 20:18:47 -0800569 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100570
Ruben Brunkcc776712015-02-17 20:18:47 -0800571 return ret;
572}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700573
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800574std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700575 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
576 auto callingPid = CameraThreadState::getCallingPid();
577 auto callingUid = CameraThreadState::getCallingUid();
578 if (checkPermission(sSystemCameraPermission, callingPid, callingUid) ||
579 getpid() == callingPid) {
580 deviceIds = &mNormalDeviceIds;
581 }
582 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800583 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700584 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800585 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800586 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800587
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700588 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800589}
590
591String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
592 Mutex::Autolock lock(mServiceLock);
593 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800594}
595
596Status CameraService::getCameraCharacteristics(const String16& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800597 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700598 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700599 if (!cameraInfo) {
600 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800601 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700602 }
603
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800604 if (!mInitialized) {
605 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800606 return STATUS_ERROR(ERROR_DISCONNECTED,
607 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700608 }
609
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700610 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
611 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
612 "characteristics for system only device %s: ", String8(cameraId).string());
613 }
614
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800615 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800616
Emilian Peevf53f66e2017-04-11 14:29:43 +0100617 status_t res = mCameraProviderManager->getCameraCharacteristics(
618 String8(cameraId).string(), cameraInfo);
619 if (res != OK) {
620 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
621 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
622 strerror(-res), res);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700623 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700624 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
625 if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
626 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
627 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
628 "for device %s", String8(cameraId).string());
629 }
Jayant Chowdhary12361932018-08-27 14:46:13 -0700630 int callingPid = CameraThreadState::getCallingPid();
631 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100632 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700633 // If it's not calling from cameraserver, check the permission only if
634 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
635 // it would've already been checked in shouldRejectSystemCameraConnection.
Emilian Peeve20c6372018-08-14 18:45:53 +0100636 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700637 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700638 !checkPermission(sCameraPermission, callingPid, callingUid)) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100639 res = cameraInfo->removePermissionEntries(
640 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
641 &tagsRemoved);
642 if (res != OK) {
643 cameraInfo->clear();
644 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
645 " characteristics needing camera permission for device %s: %s (%d)",
646 String8(cameraId).string(), strerror(-res), res);
647 }
648 }
649
650 if (!tagsRemoved.empty()) {
651 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
652 tagsRemoved.data(), tagsRemoved.size());
653 if (res != OK) {
654 cameraInfo->clear();
655 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
656 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
657 strerror(-res), res);
658 }
659 }
660
Zhijun He2b59be82013-09-25 10:14:30 -0700661 return ret;
662}
663
Ruben Brunkcc776712015-02-17 20:18:47 -0800664String8 CameraService::getFormattedCurrentTime() {
665 time_t now = time(nullptr);
666 char formattedTime[64];
667 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
668 return String8(formattedTime);
669}
670
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800671Status CameraService::getCameraVendorTagDescriptor(
672 /*out*/
673 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700674 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800675 if (!mInitialized) {
676 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800677 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800678 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800679 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
680 if (globalDescriptor != nullptr) {
681 *desc = *(globalDescriptor.get());
682 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800683 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800684}
685
Emilian Peev71c73a22017-03-21 16:35:51 +0000686Status CameraService::getCameraVendorTagCache(
687 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
688 ATRACE_CALL();
689 if (!mInitialized) {
690 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
691 return STATUS_ERROR(ERROR_DISCONNECTED,
692 "Camera subsystem not available");
693 }
694 sp<VendorTagDescriptorCache> globalCache =
695 VendorTagDescriptorCache::getGlobalVendorTagCache();
696 if (globalCache != nullptr) {
697 *cache = *(globalCache.get());
698 }
699 return Status::ok();
700}
701
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800702int CameraService::getDeviceVersion(const String8& cameraId, int* facing) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700703 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800704
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800705 int deviceVersion = 0;
706
Emilian Peevf53f66e2017-04-11 14:29:43 +0100707 status_t res;
708 hardware::hidl_version maxVersion{0,0};
709 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
710 &maxVersion);
711 if (res != OK) return -1;
712 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800713
Emilian Peevf53f66e2017-04-11 14:29:43 +0100714 hardware::CameraInfo info;
715 if (facing) {
716 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800717 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100718 *facing = info.facing;
Igor Murashkin634a5152013-02-20 17:15:11 -0800719 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100720
Igor Murashkin634a5152013-02-20 17:15:11 -0800721 return deviceVersion;
722}
723
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800724Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700725 switch(err) {
726 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800727 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800728 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800729 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
730 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800731 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800732 return STATUS_ERROR(ERROR_DISCONNECTED,
733 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700734 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800735 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
736 "Camera HAL encountered error %d: %s",
737 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700738 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800739}
740
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800741Status CameraService::makeClient(const sp<CameraService>& cameraService,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800742 const sp<IInterface>& cameraCb, const String16& packageName,
743 const std::unique_ptr<String16>& featureId, const String8& cameraId, int api1CameraId,
744 int facing, int clientPid, uid_t clientUid, int servicePid, int halVersion,
745 int deviceVersion, apiLevel effectiveApiLevel,
Ruben Brunkcc776712015-02-17 20:18:47 -0800746 /*out*/sp<BasicClient>* client) {
747
Ruben Brunkcc776712015-02-17 20:18:47 -0800748 if (halVersion < 0 || halVersion == deviceVersion) {
749 // Default path: HAL version is unspecified by caller, create CameraClient
750 // based on device version reported by the HAL.
751 switch(deviceVersion) {
752 case CAMERA_DEVICE_API_VERSION_1_0:
753 if (effectiveApiLevel == API_1) { // Camera1 API route
754 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800755 *client = new CameraClient(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800756 api1CameraId, facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700757 getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800758 } else { // Camera2 API route
759 ALOGW("Camera using old HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800760 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800761 "Camera device \"%s\" HAL version %d does not support camera2 API",
762 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800763 }
764 break;
Ruben Brunkcc776712015-02-17 20:18:47 -0800765 case CAMERA_DEVICE_API_VERSION_3_0:
766 case CAMERA_DEVICE_API_VERSION_3_1:
767 case CAMERA_DEVICE_API_VERSION_3_2:
768 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -0700769 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -0700770 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -0800771 case CAMERA_DEVICE_API_VERSION_3_6:
Ruben Brunkcc776712015-02-17 20:18:47 -0800772 if (effectiveApiLevel == API_1) { // Camera1 API route
773 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800774 *client = new Camera2Client(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800775 cameraId, api1CameraId,
776 facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700777 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800778 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800779 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
780 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800781 *client = new CameraDeviceClient(cameraService, tmp, packageName, featureId,
782 cameraId, facing, clientPid, clientUid, servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800783 }
784 break;
785 default:
786 // Should not be reachable
787 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800788 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800789 "Camera device \"%s\" has unknown HAL version %d",
790 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800791 }
792 } else {
793 // A particular HAL version is requested by caller. Create CameraClient
794 // based on the requested HAL version.
795 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
796 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
797 // Only support higher HAL version device opened as HAL1.0 device.
798 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800799 *client = new CameraClient(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800800 api1CameraId, facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700801 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800802 } else {
803 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
804 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
805 " opened as HAL %x device", halVersion, deviceVersion,
806 CAMERA_DEVICE_API_VERSION_1_0);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800807 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800808 "Camera device \"%s\" (HAL version %d) cannot be opened as HAL version %d",
809 cameraId.string(), deviceVersion, halVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800810 }
811 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800812 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800813}
814
Ruben Brunk6267b532015-04-30 17:44:07 -0700815String8 CameraService::toString(std::set<userid_t> intSet) {
816 String8 s("");
817 bool first = true;
818 for (userid_t i : intSet) {
819 if (first) {
820 s.appendFormat("%d", i);
821 first = false;
822 } else {
823 s.appendFormat(", %d", i);
824 }
825 }
826 return s;
827}
828
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800829int32_t CameraService::mapToInterface(TorchModeStatus status) {
830 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
831 switch (status) {
832 case TorchModeStatus::NOT_AVAILABLE:
833 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
834 break;
835 case TorchModeStatus::AVAILABLE_OFF:
836 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
837 break;
838 case TorchModeStatus::AVAILABLE_ON:
839 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
840 break;
841 default:
842 ALOGW("Unknown new flash status: %d", status);
843 }
844 return serviceStatus;
845}
846
847CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
848 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
849 switch (status) {
850 case CameraDeviceStatus::NOT_PRESENT:
851 serviceStatus = StatusInternal::NOT_PRESENT;
852 break;
853 case CameraDeviceStatus::PRESENT:
854 serviceStatus = StatusInternal::PRESENT;
855 break;
856 case CameraDeviceStatus::ENUMERATING:
857 serviceStatus = StatusInternal::ENUMERATING;
858 break;
859 default:
860 ALOGW("Unknown new HAL device status: %d", status);
861 }
862 return serviceStatus;
863}
864
865int32_t CameraService::mapToInterface(StatusInternal status) {
866 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
867 switch (status) {
868 case StatusInternal::NOT_PRESENT:
869 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
870 break;
871 case StatusInternal::PRESENT:
872 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
873 break;
874 case StatusInternal::ENUMERATING:
875 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
876 break;
877 case StatusInternal::NOT_AVAILABLE:
878 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
879 break;
880 case StatusInternal::UNKNOWN:
881 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
882 break;
883 default:
884 ALOGW("Unknown new internal device status: %d", status);
885 }
886 return serviceStatus;
887}
888
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800889Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -0700890 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700891
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800892 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -0800893 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800894 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800895 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800896 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800897 sp<ICameraClient>{nullptr}, id, cameraId,
898 static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800899 internalPackageName, std::unique_ptr<String16>(), uid, USE_CALLING_PID,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700900 API_1, /*shimUpdateOnly*/ true, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800901 ).isOk()) {
902 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -0700903 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800904 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700905}
906
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800907Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -0700908 /*out*/
909 CameraParameters* parameters) {
910
911 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
912
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800913 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -0700914
915 if (parameters == NULL) {
916 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800917 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700918 }
919
Ruben Brunkcc776712015-02-17 20:18:47 -0800920 String8 id = String8::format("%d", cameraId);
921
922 // Check if we already have parameters
923 {
924 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700925 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800926 auto cameraState = getCameraState(id);
927 if (cameraState == nullptr) {
928 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800929 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
930 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800931 }
932 CameraParameters p = cameraState->getShimParams();
933 if (!p.isEmpty()) {
934 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800935 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700936 }
937 }
938
Jayant Chowdhary12361932018-08-27 14:46:13 -0700939 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -0800940 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -0700941 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800942 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800943 // Error already logged by callee
944 return ret;
945 }
946
947 // Check for parameters again
948 {
949 // Scope for service lock
950 Mutex::Autolock lock(mServiceLock);
951 auto cameraState = getCameraState(id);
952 if (cameraState == nullptr) {
953 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800954 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
955 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -0700956 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800957 CameraParameters p = cameraState->getShimParams();
958 if (!p.isEmpty()) {
959 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800960 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700961 }
962 }
963
Ruben Brunkcc776712015-02-17 20:18:47 -0800964 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
965 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800966 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700967}
968
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800969// Can camera service trust the caller based on the calling UID?
970static bool isTrustedCallingUid(uid_t uid) {
971 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -0700972 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800973 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -0700974 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800975 return true;
976 default:
977 return false;
978 }
979}
980
Nicholas Sauera3620332019-04-03 14:05:17 -0700981static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
982 PermissionController pc;
983 uid = pc.getPackageUid(packageName, 0);
984 if (uid <= 0) {
985 ALOGE("Unknown package: '%s'", String8(packageName).string());
986 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
987 return BAD_VALUE;
988 }
989
990 if (userId < 0) {
991 ALOGE("Invalid user: %d", userId);
992 dprintf(err, "Invalid user: %d\n", userId);
993 return BAD_VALUE;
994 }
995
996 uid = multiuser_get_uid(userId, uid);
997 return NO_ERROR;
998}
999
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001000Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001001 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1002 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001003
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001004#ifdef __BRILLO__
1005 UNUSED(clientName8);
1006 UNUSED(clientUid);
1007 UNUSED(clientPid);
1008 UNUSED(originalClientPid);
1009#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001010 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1011 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001012 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001013 return allowed;
1014 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001015#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001016
Jayant Chowdhary12361932018-08-27 14:46:13 -07001017 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001018
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001019 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001020 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1021 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001022 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1023 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001024 }
1025
Ruben Brunkcc776712015-02-17 20:18:47 -08001026 if (getCameraState(cameraId) == nullptr) {
1027 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1028 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001029 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1030 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001031 }
1032
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001033 status_t err = checkIfDeviceIsUsable(cameraId);
1034 if (err != NO_ERROR) {
1035 switch(err) {
1036 case -ENODEV:
1037 case -EBUSY:
1038 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1039 "No camera device with ID \"%s\" currently available", cameraId.string());
1040 default:
1041 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1042 "Unknown error connecting to ID \"%s\"", cameraId.string());
1043 }
1044 }
1045 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001046}
1047
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001048Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001049 const String8& clientName8, int& clientUid, int& clientPid,
1050 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001051 int callingPid = CameraThreadState::getCallingPid();
1052 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001053
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001054 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001055 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001056 clientUid = callingUid;
1057 } else if (!isTrustedCallingUid(callingUid)) {
1058 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1059 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001060 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1061 "Untrusted caller (calling PID %d, UID %d) trying to "
1062 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1063 callingPid, callingUid, cameraId.string(),
1064 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001065 }
1066
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001067 // Check if we can trust clientPid
1068 if (clientPid == USE_CALLING_PID) {
1069 clientPid = callingPid;
1070 } else if (!isTrustedCallingUid(callingUid)) {
1071 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1072 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001073 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1074 "Untrusted caller (calling PID %d, UID %d) trying to "
1075 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1076 callingPid, callingUid, cameraId.string(),
1077 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001078 }
1079
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001080 if (shouldRejectSystemCameraConnection(cameraId)) {
1081 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1082 cameraId.c_str());
1083 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1084 "available", cameraId.string());
1085 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001086 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1087 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1088 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1089 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1090 "found while trying to query device kind", cameraId.string());
1091
1092 }
1093
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001094 // If it's not calling from cameraserver, check the permission if the
1095 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1096 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001097 if (callingPid != getpid() &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001098 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001099 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001100 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001101 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1102 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1103 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001104 }
1105
Svet Ganova453d0d2018-01-11 15:37:58 -08001106 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001107 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001108 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001109 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1110 clientPid, clientUid);
1111 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001112 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1113 "calling UID %d proc state %" PRId32 ")",
1114 clientName8.string(), clientUid, clientPid, cameraId.string(),
1115 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001116 }
1117
Michael Grooverd1d435a2018-12-18 17:39:42 -08001118 // If sensor privacy is enabled then prevent access to the camera
1119 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1120 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1121 return STATUS_ERROR_FMT(ERROR_DISABLED,
1122 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1123 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1124 }
1125
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001126 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1127 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001128 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001129 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001130
Ruben Brunk6267b532015-04-30 17:44:07 -07001131 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001132
Ruben Brunka8ca9152015-04-07 14:23:40 -07001133 // Only allow clients who are being used by the current foreground device user, unless calling
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001134 // from our own process OR the caller is using the cameraserver's HIDL interface.
1135 if (!hardware::IPCThreadState::self()->isServingCall() && callingPid != getpid() &&
1136 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001137 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1138 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1139 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001140 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1141 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1142 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001143 }
1144
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001145 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001146}
1147
1148status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1149 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001150 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001151 if (cameraState == nullptr) {
1152 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1153 cameraId.string());
1154 return -ENODEV;
1155 }
1156
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001157 StatusInternal currentStatus = cameraState->getStatus();
1158 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001159 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1160 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001161 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001162 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001163 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1164 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001165 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001166 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001167
Ruben Brunkcc776712015-02-17 20:18:47 -08001168 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001169}
1170
Ruben Brunkcc776712015-02-17 20:18:47 -08001171void CameraService::finishConnectLocked(const sp<BasicClient>& client,
1172 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001173
Ruben Brunkcc776712015-02-17 20:18:47 -08001174 // Make a descriptor for the incoming client
1175 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
1176 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1177
1178 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1179 String8(client->getPackageName()));
1180
1181 if (evicted.size() > 0) {
1182 // This should never happen - clients should already have been removed in disconnect
1183 for (auto& i : evicted) {
1184 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1185 __FUNCTION__, i->getKey().string());
1186 }
1187
1188 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1189 __FUNCTION__);
1190 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001191
1192 // And register a death notification for the client callback. Do
1193 // this last to avoid Binder policy where a nested Binder
1194 // transaction might be pre-empted to service the client death
1195 // notification if the client process dies before linkToDeath is
1196 // invoked.
1197 sp<IBinder> remoteCallback = client->getRemote();
1198 if (remoteCallback != nullptr) {
1199 remoteCallback->linkToDeath(this);
1200 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001201}
1202
1203status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1204 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
1205 /*out*/
1206 sp<BasicClient>* client,
1207 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001208 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001209 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001210 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001211 DescriptorPtr clientDescriptor;
1212 {
1213 if (effectiveApiLevel == API_1) {
1214 // If we are using API1, any existing client for this camera ID with the same remote
1215 // should be returned rather than evicted to allow MediaRecorder to work properly.
1216
1217 auto current = mActiveClientManager.get(cameraId);
1218 if (current != nullptr) {
1219 auto clientSp = current->getValue();
1220 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001221 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1222 ALOGW("CameraService connect called from same client, but with a different"
1223 " API level, evicting prior client...");
1224 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001225 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001226 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001227 *client = clientSp;
1228 return NO_ERROR;
1229 }
1230 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001231 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001232 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001233
Ruben Brunkcc776712015-02-17 20:18:47 -08001234 // Get current active client PIDs
1235 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1236 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001237
Emilian Peev8131a262017-02-01 12:33:43 +00001238 std::vector<int> priorityScores(ownerPids.size());
1239 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001240
Emilian Peev8131a262017-02-01 12:33:43 +00001241 // Get priority scores of all active PIDs
1242 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1243 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1244 /*out*/&priorityScores[0]);
1245 if (err != OK) {
1246 ALOGE("%s: Priority score query failed: %d",
1247 __FUNCTION__, err);
1248 return err;
1249 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001250
Ruben Brunkcc776712015-02-17 20:18:47 -08001251 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001252 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001253 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001254 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001255 resource_policy::ClientPriority(priorityScores[i], states[i],
1256 /* isVendorClient won't get copied over*/ false));
Ruben Brunkcc776712015-02-17 20:18:47 -08001257 }
1258 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001259
Ruben Brunkcc776712015-02-17 20:18:47 -08001260 // Get state for the given cameraId
1261 auto state = getCameraState(cameraId);
1262 if (state == nullptr) {
1263 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1264 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001265 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001266 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001267 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001268
1269 // Make descriptor for incoming client
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001270 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001271 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1272 state->getConflicting(),
Emilian Peev8131a262017-02-01 12:33:43 +00001273 priorityScores[priorityScores.size() - 1],
1274 clientPid,
1275 states[states.size() - 1]);
Ruben Brunkcc776712015-02-17 20:18:47 -08001276
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001277 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1278
Ruben Brunkcc776712015-02-17 20:18:47 -08001279 // Find clients that would be evicted
1280 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1281
1282 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1283 // background, so we cannot do evictions
1284 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1285 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1286 " priority).", clientPid);
1287
1288 sp<BasicClient> clientSp = clientDescriptor->getValue();
1289 String8 curTime = getFormattedCurrentTime();
1290 auto incompatibleClients =
1291 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1292
1293 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001294 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001295 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001296 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001297
1298 for (auto& i : incompatibleClients) {
1299 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001300 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1301 i->getKey().string(),
1302 String8{i->getValue()->getPackageName()}.string(),
1303 i->getOwnerId(), i->getPriority().getScore(),
1304 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001305 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001306 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001307 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001308 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001309 }
1310
1311 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001312 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001313 mEventLog.add(msg);
1314
1315 return -EBUSY;
1316 }
1317
1318 for (auto& i : evicted) {
1319 sp<BasicClient> clientSp = i->getValue();
1320 if (clientSp.get() == nullptr) {
1321 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1322
1323 // TODO: Remove this
1324 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1325 __FUNCTION__);
1326 mActiveClientManager.remove(i);
1327 continue;
1328 }
1329
1330 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1331 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001332 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001333
Ruben Brunkcc776712015-02-17 20:18:47 -08001334 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001335 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001336 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1337 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001338 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001339 i->getOwnerId(), i->getPriority().getScore(),
1340 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001341 packageName.string(), clientPid, clientPriority.getScore(),
1342 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001343
1344 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001345 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001346 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001347 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001348 }
1349
Ruben Brunkcc776712015-02-17 20:18:47 -08001350 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1351 // other clients from connecting in mServiceLockWrapper if held
1352 mServiceLock.unlock();
1353
1354 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001355 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001356
1357 // Destroy evicted clients
1358 for (auto& i : evictedClients) {
1359 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001360 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001361 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001362
Jayant Chowdhary12361932018-08-27 14:46:13 -07001363 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001364
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001365 for (const auto& i : evictedClients) {
1366 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1367 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1368 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1369 if (ret == TIMED_OUT) {
1370 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1371 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1372 mActiveClientManager.toString().string());
1373 return -EBUSY;
1374 }
1375 if (ret != NO_ERROR) {
1376 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1377 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1378 ret, mActiveClientManager.toString().string());
1379 return ret;
1380 }
1381 }
1382
1383 evictedClients.clear();
1384
Ruben Brunkcc776712015-02-17 20:18:47 -08001385 // Once clients have been disconnected, relock
1386 mServiceLock.lock();
1387
1388 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1389 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1390 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001391 }
1392
Ruben Brunkcc776712015-02-17 20:18:47 -08001393 *partial = clientDescriptor;
1394 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001395}
1396
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001397Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001398 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001399 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001400 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001401 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001402 int clientPid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001403 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001404 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001405
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001406 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001407 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001408
1409 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001410 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001411 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001412 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, std::unique_ptr<String16>(),
1413 clientUid, clientPid, API_1, /*shimUpdateOnly*/ false, /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001414
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001415 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001416 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001417 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001418 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001419 }
1420
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001421 *device = client;
1422 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001423}
1424
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001425Status CameraService::connectLegacy(
Zhijun Heb10cdad2014-06-16 16:38:35 -07001426 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001427 int api1CameraId, int halVersion,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001428 const String16& clientPackageName,
Zhijun Heb10cdad2014-06-16 16:38:35 -07001429 int clientUid,
1430 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001431 sp<ICamera>* device) {
Zhijun Heb10cdad2014-06-16 16:38:35 -07001432
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001433 ATRACE_CALL();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001434 String8 id = cameraIdIntToStr(api1CameraId);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001435
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001436 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001437 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001438 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId, halVersion,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001439 clientPackageName, std::unique_ptr<String16>(), clientUid, USE_CALLING_PID, API_1,
1440 /*shimUpdateOnly*/ false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001441
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001442 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001443 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001444 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001445 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001446 }
1447
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001448 *device = client;
1449 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001450}
1451
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001452bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1453 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001454 // If the client is not a vendor client, don't add listener if
1455 // a) the camera is a publicly hidden secure camera OR
1456 // b) the camera is a system only camera and the client doesn't
1457 // have android.permission.SYSTEM_CAMERA permissions.
1458 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1459 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1460 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001461 return true;
1462 }
1463 return false;
1464}
1465
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001466bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1467 // Rules for rejection:
1468 // 1) If cameraserver tries to access this camera device, accept the
1469 // connection.
1470 // 2) The camera device is a publicly hidden secure camera device AND some
1471 // component is trying to access it on a non-hwbinder thread (generally a non HAL client),
1472 // reject it.
1473 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1474 // and the serving thread is a non hwbinder thread, the client must have
1475 // android.permission.SYSTEM_CAMERA permissions to connect.
1476
1477 int cPid = CameraThreadState::getCallingPid();
1478 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001479 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1480 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
1481 ALOGE("%s: Invalid camera id %s, ", __FUNCTION__, cameraId.c_str());
1482 return true;
1483 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001484
1485 // (1) Cameraserver trying to connect, accept.
1486 if (CameraThreadState::getCallingPid() == getpid()) {
1487 return false;
1488 }
1489 // (2)
1490 if (!hardware::IPCThreadState::self()->isServingCall() &&
1491 systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
1492 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1493 return true;
1494 }
1495 // (3) Here we only check for permissions if it is a system only camera device. This is since
1496 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1497 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1498 // same behavior for system camera devices.
1499 if (!hardware::IPCThreadState::self()->isServingCall() &&
1500 systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1501 !hasPermissionsForSystemCamera(cPid, cUid)) {
1502 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1503 cameraId.c_str());
1504 return true;
1505 }
1506
1507 return false;
1508}
1509
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001510Status CameraService::connectDevice(
1511 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001512 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001513 const String16& clientPackageName,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001514 const std::unique_ptr<String16>& clientFeatureId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001515 int clientUid,
1516 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001517 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001518
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001519 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001520 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001521 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001522 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001523 String16 clientPackageNameAdj = clientPackageName;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001524
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001525 if (hardware::IPCThreadState::self()->isServingCall()) {
1526 std::string vendorClient =
1527 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1528 clientPackageNameAdj = String16(vendorClient.c_str());
1529 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001530 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001531 /*api1CameraId*/-1,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001532 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageNameAdj, clientFeatureId,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001533 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001534
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001535 if(!ret.isOk()) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001536 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageNameAdj),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001537 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001538 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001539 }
1540
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001541 *device = client;
1542 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001543}
1544
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001545template<class CALLBACK, class CLIENT>
1546Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001547 int api1CameraId, int halVersion, const String16& clientPackageName,
1548 const std::unique_ptr<String16>& clientFeatureId, int clientUid, int clientPid,
1549 apiLevel effectiveApiLevel, bool shimUpdateOnly,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001550 /*out*/sp<CLIENT>& device) {
1551 binder::Status ret = binder::Status::ok();
1552
1553 String8 clientName8(clientPackageName);
1554
1555 int originalClientPid = 0;
1556
1557 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) for HAL version %s and "
1558 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
1559 (halVersion == -1) ? "default" : std::to_string(halVersion).c_str(),
1560 static_cast<int>(effectiveApiLevel));
1561
1562 sp<CLIENT> client = nullptr;
1563 {
1564 // Acquire mServiceLock and prevent other clients from connecting
1565 std::unique_ptr<AutoConditionLock> lock =
1566 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1567
1568 if (lock == nullptr) {
1569 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1570 , clientPid);
1571 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1572 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1573 cameraId.string(), clientName8.string(), clientPid);
1574 }
1575
1576 // Enforce client permissions and do basic sanity checks
1577 if(!(ret = validateConnectLocked(cameraId, clientName8,
1578 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1579 return ret;
1580 }
1581
1582 // Check the shim parameters after acquiring lock, if they have already been updated and
1583 // we were doing a shim update, return immediately
1584 if (shimUpdateOnly) {
1585 auto cameraState = getCameraState(cameraId);
1586 if (cameraState != nullptr) {
1587 if (!cameraState->getShimParams().isEmpty()) return ret;
1588 }
1589 }
1590
1591 status_t err;
1592
1593 sp<BasicClient> clientTmp = nullptr;
1594 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1595 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
1596 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
1597 /*out*/&partial)) != NO_ERROR) {
1598 switch (err) {
1599 case -ENODEV:
1600 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1601 "No camera device with ID \"%s\" currently available",
1602 cameraId.string());
1603 case -EBUSY:
1604 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1605 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1606 cameraId.string());
1607 default:
1608 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1609 "Unexpected error %s (%d) opening camera \"%s\"",
1610 strerror(-err), err, cameraId.string());
1611 }
1612 }
1613
1614 if (clientTmp.get() != nullptr) {
1615 // Handle special case for API1 MediaRecorder where the existing client is returned
1616 device = static_cast<CLIENT*>(clientTmp.get());
1617 return ret;
1618 }
1619
1620 // give flashlight a chance to close devices if necessary.
1621 mFlashlight->prepareDeviceOpen(cameraId);
1622
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001623 int facing = -1;
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001624 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001625 if (facing == -1) {
1626 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1627 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1628 "Unable to get camera device \"%s\" facing", cameraId.string());
1629 }
1630
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001631 sp<BasicClient> tmp = nullptr;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001632 if(!(ret = makeClient(this, cameraCb, clientPackageName, clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001633 cameraId, api1CameraId, facing,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001634 clientPid, clientUid, getpid(),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001635 halVersion, deviceVersion, effectiveApiLevel,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001636 /*out*/&tmp)).isOk()) {
1637 return ret;
1638 }
1639 client = static_cast<CLIENT*>(tmp.get());
1640
1641 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1642 __FUNCTION__);
1643
Emilian Peevbd8c5032018-02-14 23:05:40 +00001644 err = client->initialize(mCameraProviderManager, mMonitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001645 if (err != OK) {
1646 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001647 // Errors could be from the HAL module open call or from AppOpsManager
1648 switch(err) {
1649 case BAD_VALUE:
1650 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1651 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1652 case -EBUSY:
1653 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1654 "Camera \"%s\" is already open", cameraId.string());
1655 case -EUSERS:
1656 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1657 "Too many cameras already open, cannot open camera \"%s\"",
1658 cameraId.string());
1659 case PERMISSION_DENIED:
1660 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1661 "No permission to open camera \"%s\"", cameraId.string());
1662 case -EACCES:
1663 return STATUS_ERROR_FMT(ERROR_DISABLED,
1664 "Camera \"%s\" disabled by policy", cameraId.string());
1665 case -ENODEV:
1666 default:
1667 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1668 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1669 strerror(-err), err);
1670 }
1671 }
1672
1673 // Update shim paremeters for legacy clients
1674 if (effectiveApiLevel == API_1) {
1675 // Assume we have always received a Client subclass for API1
1676 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1677 String8 rawParams = shimClient->getParameters();
1678 CameraParameters params(rawParams);
1679
1680 auto cameraState = getCameraState(cameraId);
1681 if (cameraState != nullptr) {
1682 cameraState->setShimParams(params);
1683 } else {
1684 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1685 __FUNCTION__, cameraId.string());
1686 }
1687 }
1688
1689 if (shimUpdateOnly) {
1690 // If only updating legacy shim parameters, immediately disconnect client
1691 mServiceLock.unlock();
1692 client->disconnect();
1693 mServiceLock.lock();
1694 } else {
1695 // Otherwise, add client to active clients list
1696 finishConnectLocked(client, partial);
1697 }
1698 } // lock is destroyed, allow further connect calls
1699
1700 // Important: release the mutex here so the client can call back into the service from its
1701 // destructor (can be at the end of the call)
1702 device = client;
1703 return ret;
1704}
1705
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001706status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
1707 if (offlineClient.get() == nullptr) {
1708 return BAD_VALUE;
1709 }
1710
1711 {
1712 // Acquire mServiceLock and prevent other clients from connecting
1713 std::unique_ptr<AutoConditionLock> lock =
1714 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1715
1716 if (lock == nullptr) {
1717 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
1718 , __FUNCTION__, offlineClient->getClientPid());
1719 return TIMED_OUT;
1720 }
1721
1722 auto onlineClientDesc = mActiveClientManager.get(cameraId);
1723 if (onlineClientDesc.get() == nullptr) {
1724 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
1725 cameraId.c_str());
1726 return BAD_VALUE;
1727 }
1728
1729 // Offline clients do not evict or conflict with other online devices. Resource sharing
1730 // conflicts are handled by the camera provider which will either succeed or fail before
1731 // reaching this method.
1732 const auto& onlinePriority = onlineClientDesc->getPriority();
1733 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
1734 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
1735 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
1736 onlineClientDesc->getOwnerId(), onlinePriority.getState());
1737
1738 // Allow only one offline device per camera
1739 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
1740 if (!incompatibleClients.empty()) {
1741 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
1742 return BAD_VALUE;
1743 }
1744
1745 auto err = offlineClient->initialize(mCameraProviderManager, mMonitorTags);
1746 if (err != OK) {
1747 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
1748 return err;
1749 }
1750
1751 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
1752 if (evicted.size() > 0) {
1753 for (auto& i : evicted) {
1754 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
1755 __FUNCTION__, i->getKey().string());
1756 }
1757
1758 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
1759 "properly", __FUNCTION__);
1760
1761 return BAD_VALUE;
1762 }
1763
1764 logConnectedOffline(offlineClientDesc->getKey(),
1765 static_cast<int>(offlineClientDesc->getOwnerId()),
1766 String8(offlineClient->getPackageName()));
1767
1768 sp<IBinder> remoteCallback = offlineClient->getRemote();
1769 if (remoteCallback != nullptr) {
1770 remoteCallback->linkToDeath(this);
1771 }
1772 } // lock is destroyed, allow further connect calls
1773
1774 return OK;
1775}
1776
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001777Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001778 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001779 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001780
1781 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001782 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001783 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001784 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1785 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001786 }
1787
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001788 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07001789 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001790
1791 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001792 auto state = getCameraState(id);
1793 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001794 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001795 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1796 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001797 }
1798
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001799 StatusInternal cameraStatus = state->getStatus();
1800 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001801 cameraStatus != StatusInternal::NOT_AVAILABLE) {
1802 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001803 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1804 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001805 }
1806
1807 {
1808 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001809 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001810 status_t err = getTorchStatusLocked(id, &status);
1811 if (err != OK) {
1812 if (err == NAME_NOT_FOUND) {
1813 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1814 "Camera \"%s\" does not have a flash unit", id.string());
1815 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001816 ALOGE("%s: getting current torch status failed for camera %s",
1817 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001818 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1819 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
1820 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001821 }
1822
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001823 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001824 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001825 ALOGE("%s: torch mode of camera %s is not available because "
1826 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001827 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1828 "Torch for camera \"%s\" is not available due to an existing camera user",
1829 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001830 } else {
1831 ALOGE("%s: torch mode of camera %s is not available due to "
1832 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001833 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1834 "Torch for camera \"%s\" is not available due to insufficient resources",
1835 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001836 }
1837 }
1838 }
1839
Ruben Brunk99e69712015-05-26 17:25:07 -07001840 {
1841 // Update UID map - this is used in the torch status changed callbacks, so must be done
1842 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001843 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001844 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1845 mTorchUidMap[id].first = uid;
1846 mTorchUidMap[id].second = uid;
1847 } else {
1848 // Set the pending UID
1849 mTorchUidMap[id].first = uid;
1850 }
1851 }
1852
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001853 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001854
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001855 if (err != OK) {
1856 int32_t errorCode;
1857 String8 msg;
1858 switch (err) {
1859 case -ENOSYS:
1860 msg = String8::format("Camera \"%s\" has no flashlight",
1861 id.string());
1862 errorCode = ERROR_ILLEGAL_ARGUMENT;
1863 break;
1864 default:
1865 msg = String8::format(
1866 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1867 id.string(), enabled, strerror(-err), err);
1868 errorCode = ERROR_INVALID_OPERATION;
1869 }
1870 ALOGE("%s: %s", __FUNCTION__, msg.string());
1871 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001872 }
1873
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001874 {
1875 // update the link to client's death
1876 Mutex::Autolock al(mTorchClientMapMutex);
1877 ssize_t index = mTorchClientMap.indexOfKey(id);
1878 if (enabled) {
1879 if (index == NAME_NOT_FOUND) {
1880 mTorchClientMap.add(id, clientBinder);
1881 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001882 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001883 mTorchClientMap.replaceValueAt(index, clientBinder);
1884 }
1885 clientBinder->linkToDeath(this);
1886 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001887 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001888 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001889 }
1890
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07001891 int clientPid = CameraThreadState::getCallingPid();
1892 const char *id_cstr = id.c_str();
1893 const char *torchState = enabled ? "on" : "off";
1894 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
1895 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001896 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001897}
1898
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001899Status CameraService::notifySystemEvent(int32_t eventId,
1900 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001901 const int pid = CameraThreadState::getCallingPid();
1902 const int selfPid = getpid();
1903
1904 // Permission checks
1905 if (pid != selfPid) {
1906 // Ensure we're being called by system_server, or similar process with
1907 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001908 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001909 const int uid = CameraThreadState::getCallingUid();
1910 ALOGE("Permission Denial: cannot send updates to camera service about system"
1911 " events from pid=%d, uid=%d", pid, uid);
1912 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09001913 "No permission to send updates to camera service about system events"
1914 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001915 }
1916 }
1917
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001918 ATRACE_CALL();
1919
Ruben Brunk36597b22015-03-20 22:15:57 -07001920 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001921 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001922 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07001923 // from a system server crash
1924 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08001925 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001926 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07001927 break;
1928 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001929 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07001930 default: {
1931 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1932 eventId);
1933 break;
1934 }
1935 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001936 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07001937}
1938
Emilian Peev53722fa2019-02-22 17:47:20 -08001939void CameraService::notifyMonitoredUids() {
1940 Mutex::Autolock lock(mStatusListenerLock);
1941
1942 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001943 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08001944 if (!ret.isOk()) {
1945 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
1946 ret.exceptionCode());
1947 }
1948 }
1949}
1950
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08001951Status CameraService::notifyDeviceStateChange(int64_t newState) {
1952 const int pid = CameraThreadState::getCallingPid();
1953 const int selfPid = getpid();
1954
1955 // Permission checks
1956 if (pid != selfPid) {
1957 // Ensure we're being called by system_server, or similar process with
1958 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001959 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08001960 const int uid = CameraThreadState::getCallingUid();
1961 ALOGE("Permission Denial: cannot send updates to camera service about device"
1962 " state changes from pid=%d, uid=%d", pid, uid);
1963 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1964 "No permission to send updates to camera service about device state"
1965 " changes from pid=%d, uid=%d", pid, uid);
1966 }
1967 }
1968
1969 ATRACE_CALL();
1970
1971 using hardware::camera::provider::V2_5::DeviceState;
1972 hardware::hidl_bitfield<DeviceState> newDeviceState{};
1973 if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
1974 newDeviceState |= DeviceState::BACK_COVERED;
1975 }
1976 if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
1977 newDeviceState |= DeviceState::FRONT_COVERED;
1978 }
1979 if (newState & ICameraService::DEVICE_STATE_FOLDED) {
1980 newDeviceState |= DeviceState::FOLDED;
1981 }
1982 // Only map vendor bits directly
1983 uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
1984 newDeviceState |= vendorBits;
1985
1986 ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
1987 Mutex::Autolock l(mServiceLock);
1988 mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
1989
1990 return Status::ok();
1991}
1992
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001993Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
1994 /*out*/
1995 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001996 return addListenerHelper(listener, cameraStatuses);
1997}
1998
1999Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2000 /*out*/
2001 std::vector<hardware::CameraStatus> *cameraStatuses,
2002 bool isVendorListener) {
2003
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002004 ATRACE_CALL();
2005
Igor Murashkinbfc99152013-02-27 12:55:20 -08002006 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002007
Ruben Brunk3450ba72015-06-16 11:00:37 -07002008 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002009 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002010 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002011 }
2012
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002013 auto clientUid = CameraThreadState::getCallingUid();
2014 auto clientPid = CameraThreadState::getCallingPid();
2015
Igor Murashkinbfc99152013-02-27 12:55:20 -08002016 Mutex::Autolock lock(mServiceLock);
2017
Ruben Brunkcc776712015-02-17 20:18:47 -08002018 {
2019 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002020 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002021 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002022 ALOGW("%s: Tried to add listener %p which was already subscribed",
2023 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002024 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002025 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002026 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002027
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002028 sp<ServiceListener> serviceListener =
2029 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002030 auto ret = serviceListener->initialize();
2031 if (ret != NO_ERROR) {
2032 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2033 strerror(-ret), ret);
2034 ALOGE("%s: %s", __FUNCTION__, msg.string());
2035 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2036 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002037 // The listener still needs to be added to the list of listeners, regardless of what
2038 // permissions the listener process has / whether it is a vendor listener. Since it might be
2039 // eligible to listen to other camera ids.
2040 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002041 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002042 }
2043
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002044 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002045 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002046 Mutex::Autolock lock(mCameraStatesLock);
2047 for (auto& i : mCameraStates) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002048 cameraStatuses->emplace_back(i.first, mapToInterface(i.second->getStatus()));
Igor Murashkincba2c162013-03-20 15:56:31 -07002049 }
2050 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002051 // Remove the camera statuses that should be hidden from the client, we do
2052 // this after collecting the states in order to avoid holding
2053 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2054 // the same time.
2055 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2056 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2057 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2058 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2059 ALOGE("%s: Invalid camera id %s, skipping status update",
2060 __FUNCTION__, s.cameraId.c_str());
2061 return true;
2062 }
2063 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2064 clientUid);}), cameraStatuses->end());
2065
Igor Murashkincba2c162013-03-20 15:56:31 -07002066
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002067 /*
2068 * Immediately signal current torch status to this listener only
2069 * This may be a subset of all the devices, so don't include it in the response directly
2070 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002071 {
2072 Mutex::Autolock al(mTorchStatusMutex);
2073 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002074 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002075 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002076 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002077 }
2078
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002079 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002080}
Ruben Brunkcc776712015-02-17 20:18:47 -08002081
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002082Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002083 ATRACE_CALL();
2084
Igor Murashkinbfc99152013-02-27 12:55:20 -08002085 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2086
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002087 if (listener == 0) {
2088 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002089 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002090 }
2091
Igor Murashkinbfc99152013-02-27 12:55:20 -08002092 Mutex::Autolock lock(mServiceLock);
2093
Ruben Brunkcc776712015-02-17 20:18:47 -08002094 {
2095 Mutex::Autolock lock(mStatusListenerLock);
2096 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002097 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2098 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2099 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002100 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002101 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002102 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002103 }
2104 }
2105
2106 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2107 __FUNCTION__, listener.get());
2108
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002109 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002110}
2111
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002112Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002113
2114 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002115 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2116
2117 if (parameters == NULL) {
2118 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002119 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002120 }
2121
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002122 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002123
2124 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002125 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002126 // Error logged by caller
2127 return ret;
2128 }
2129
2130 String8 shimParamsString8 = shimParams.flatten();
2131 String16 shimParamsString16 = String16(shimParamsString8);
2132
2133 *parameters = shimParamsString16;
2134
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002135 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002136}
2137
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002138Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2139 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002140 ATRACE_CALL();
2141
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002142 const String8 id = String8(cameraId);
2143
2144 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002145
2146 switch (apiVersion) {
2147 case API_VERSION_1:
2148 case API_VERSION_2:
2149 break;
2150 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002151 String8 msg = String8::format("Unknown API version %d", apiVersion);
2152 ALOGE("%s: %s", __FUNCTION__, msg.string());
2153 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002154 }
2155
Emilian Peev28ad2ea2017-02-07 16:14:32 +00002156 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002157 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002158 case CAMERA_DEVICE_API_VERSION_1_0:
2159 case CAMERA_DEVICE_API_VERSION_3_0:
2160 case CAMERA_DEVICE_API_VERSION_3_1:
2161 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002162 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2163 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002164 *isSupported = false;
2165 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002166 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2167 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002168 *isSupported = true;
2169 }
2170 break;
2171 case CAMERA_DEVICE_API_VERSION_3_2:
2172 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07002173 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002174 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -08002175 case CAMERA_DEVICE_API_VERSION_3_6:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002176 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2177 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002178 *isSupported = true;
2179 break;
2180 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002181 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002182 ALOGE("%s: %s", __FUNCTION__, msg.string());
2183 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002184 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002185 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002186 String8 msg = String8::format("Unknown device version %x for device %s",
2187 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002188 ALOGE("%s: %s", __FUNCTION__, msg.string());
2189 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2190 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002191 }
2192
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002193 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002194}
2195
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002196Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2197 /*out*/ bool *isSupported) {
2198 ATRACE_CALL();
2199
2200 const String8 id = String8(cameraId);
2201
2202 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2203 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2204
2205 return Status::ok();
2206}
2207
Ruben Brunkcc776712015-02-17 20:18:47 -08002208void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002209 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002210 for (auto& i : mActiveClientManager.getAll()) {
2211 auto clientSp = i->getValue();
2212 if (clientSp.get() == client) {
2213 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002214 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002215 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002216 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002217}
2218
Ruben Brunkcc776712015-02-17 20:18:47 -08002219bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002220 bool ret = false;
2221 {
2222 // Acquire mServiceLock and prevent other clients from connecting
2223 std::unique_ptr<AutoConditionLock> lock =
2224 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002225
Igor Murashkin634a5152013-02-20 17:15:11 -08002226
Ruben Brunkcc776712015-02-17 20:18:47 -08002227 std::vector<sp<BasicClient>> evicted;
2228 for (auto& i : mActiveClientManager.getAll()) {
2229 auto clientSp = i->getValue();
2230 if (clientSp.get() == nullptr) {
2231 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2232 mActiveClientManager.remove(i);
2233 continue;
2234 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002235 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002236 mActiveClientManager.remove(i);
2237 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002238
Ruben Brunkcc776712015-02-17 20:18:47 -08002239 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002240 clientSp->notifyError(
2241 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002242 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002243 }
2244 }
2245
Ruben Brunkcc776712015-02-17 20:18:47 -08002246 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2247 // other clients from connecting in mServiceLockWrapper if held
2248 mServiceLock.unlock();
2249
Ruben Brunk36597b22015-03-20 22:15:57 -07002250 // Do not clear caller identity, remote caller should be client proccess
2251
Ruben Brunkcc776712015-02-17 20:18:47 -08002252 for (auto& i : evicted) {
2253 if (i.get() != nullptr) {
2254 i->disconnect();
2255 ret = true;
2256 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002257 }
2258
Ruben Brunkcc776712015-02-17 20:18:47 -08002259 // Reacquire mServiceLock
2260 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002261
Ruben Brunkcc776712015-02-17 20:18:47 -08002262 } // lock is destroyed, allow further connect calls
2263
2264 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002265}
2266
Ruben Brunkcc776712015-02-17 20:18:47 -08002267std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2268 const String8& cameraId) const {
2269 std::shared_ptr<CameraState> state;
2270 {
2271 Mutex::Autolock lock(mCameraStatesLock);
2272 auto iter = mCameraStates.find(cameraId);
2273 if (iter != mCameraStates.end()) {
2274 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002275 }
2276 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002277 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002278}
2279
Ruben Brunkcc776712015-02-17 20:18:47 -08002280sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2281 // Remove from active clients list
2282 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2283 if (clientDescriptorPtr == nullptr) {
2284 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2285 cameraId.string());
2286 return sp<BasicClient>{nullptr};
2287 }
2288
2289 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07002290}
2291
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002292void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002293 // Acquire mServiceLock and prevent other clients from connecting
2294 std::unique_ptr<AutoConditionLock> lock =
2295 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2296
Ruben Brunk6267b532015-04-30 17:44:07 -07002297 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002298 for (size_t i = 0; i < newUserIds.size(); i++) {
2299 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002300 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002301 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002302 return;
2303 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002304 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002305 }
2306
Ruben Brunka8ca9152015-04-07 14:23:40 -07002307
Ruben Brunk6267b532015-04-30 17:44:07 -07002308 if (newAllowedUsers == mAllowedUsers) {
2309 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2310 return;
2311 }
2312
2313 logUserSwitch(mAllowedUsers, newAllowedUsers);
2314
2315 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002316
2317 // Current user has switched, evict all current clients.
2318 std::vector<sp<BasicClient>> evicted;
2319 for (auto& i : mActiveClientManager.getAll()) {
2320 auto clientSp = i->getValue();
2321
2322 if (clientSp.get() == nullptr) {
2323 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2324 continue;
2325 }
2326
Ruben Brunk6267b532015-04-30 17:44:07 -07002327 // Don't evict clients that are still allowed.
2328 uid_t clientUid = clientSp->getClientUid();
2329 userid_t clientUserId = multiuser_get_user_id(clientUid);
2330 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2331 continue;
2332 }
2333
Ruben Brunk36597b22015-03-20 22:15:57 -07002334 evicted.push_back(clientSp);
2335
2336 String8 curTime = getFormattedCurrentTime();
2337
2338 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2339 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002340
Ruben Brunk36597b22015-03-20 22:15:57 -07002341 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002342 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002343 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2344 " to user switch.", i->getKey().string(),
2345 String8{clientSp->getPackageName()}.string(),
2346 i->getOwnerId(), i->getPriority().getScore(),
2347 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002348
2349 }
2350
2351 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2352 // blocking other clients from connecting in mServiceLockWrapper if held.
2353 mServiceLock.unlock();
2354
2355 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002356 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002357
2358 for (auto& i : evicted) {
2359 i->disconnect();
2360 }
2361
Jayant Chowdhary12361932018-08-27 14:46:13 -07002362 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002363
2364 // Reacquire mServiceLock
2365 mServiceLock.lock();
2366}
Ruben Brunkcc776712015-02-17 20:18:47 -08002367
Ruben Brunka8ca9152015-04-07 14:23:40 -07002368void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002369 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002370 Mutex::Autolock l(mLogLock);
2371 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002372}
2373
Ruben Brunka8ca9152015-04-07 14:23:40 -07002374void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002375 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002376 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002377 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002378 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002379}
2380
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002381void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
2382 const char* clientPackage) {
2383 // Log the clients evicted
2384 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
2385 cameraId, clientPackage, clientPid));
2386}
2387
Ruben Brunka8ca9152015-04-07 14:23:40 -07002388void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002389 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002390 // Log the clients evicted
2391 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002392 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002393}
2394
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002395void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
2396 const char* clientPackage) {
2397 // Log the clients evicted
2398 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
2399 clientPackage, clientPid));
2400}
2401
Ruben Brunka8ca9152015-04-07 14:23:40 -07002402void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002403 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002404 // Log the client rejected
2405 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002406 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002407}
2408
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002409void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
2410 // Log torch event
2411 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
2412 torchState, clientPid));
2413}
2414
Ruben Brunk6267b532015-04-30 17:44:07 -07002415void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
2416 const std::set<userid_t>& newUserIds) {
2417 String8 newUsers = toString(newUserIds);
2418 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002419 if (oldUsers.size() == 0) {
2420 oldUsers = "<None>";
2421 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07002422 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002423 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07002424 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002425}
2426
2427void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
2428 // Log the device removal
2429 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
2430}
2431
2432void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
2433 // Log the device removal
2434 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
2435}
2436
2437void CameraService::logClientDied(int clientPid, const char* reason) {
2438 // Log the device removal
2439 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07002440}
2441
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002442void CameraService::logServiceError(const char* msg, int errorCode) {
2443 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002444 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002445}
2446
Ruben Brunk36597b22015-03-20 22:15:57 -07002447status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
2448 uint32_t flags) {
2449
Mathias Agopian65ab4712010-07-14 17:59:35 -07002450 // Permission checks
2451 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002452 case SHELL_COMMAND_TRANSACTION: {
2453 int in = data.readFileDescriptor();
2454 int out = data.readFileDescriptor();
2455 int err = data.readFileDescriptor();
2456 int argc = data.readInt32();
2457 Vector<String16> args;
2458 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
2459 args.add(data.readString16());
2460 }
2461 sp<IBinder> unusedCallback;
2462 sp<IResultReceiver> resultReceiver;
2463 status_t status;
2464 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
2465 return status;
2466 }
2467 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
2468 return status;
2469 }
2470 status = shellCommand(in, out, err, args);
2471 if (resultReceiver != nullptr) {
2472 resultReceiver->send(status);
2473 }
2474 return NO_ERROR;
2475 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002476 }
2477
2478 return BnCameraService::onTransact(code, data, reply, flags);
2479}
2480
Mathias Agopian65ab4712010-07-14 17:59:35 -07002481// We share the media players for shutter and recording sound for all clients.
2482// A reference count is kept to determine when we will actually release the
2483// media players.
2484
Jaekyun Seokef498052018-03-23 13:09:44 +09002485sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
2486 sp<MediaPlayer> mp = new MediaPlayer();
2487 status_t error;
2488 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08002489 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09002490 error = mp->prepare();
2491 }
2492 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002493 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09002494 mp->disconnect();
2495 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002496 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002497 }
2498 return mp;
2499}
2500
username5755fea2018-12-27 09:48:08 +08002501void CameraService::increaseSoundRef() {
2502 Mutex::Autolock lock(mSoundLock);
2503 mSoundRef++;
2504}
2505
2506void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002507 ATRACE_CALL();
2508
username5755fea2018-12-27 09:48:08 +08002509 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
2510 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
2511 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
2512 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
2513 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2514 }
2515 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
2516 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
2517 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
2518 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002519 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08002520 }
2521 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
2522 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
2523 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
2524 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2525 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002526 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002527}
2528
username5755fea2018-12-27 09:48:08 +08002529void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002530 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002531 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002532 if (--mSoundRef) return;
2533
2534 for (int i = 0; i < NUM_SOUNDS; i++) {
2535 if (mSoundPlayer[i] != 0) {
2536 mSoundPlayer[i]->disconnect();
2537 mSoundPlayer[i].clear();
2538 }
2539 }
2540}
2541
2542void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002543 ATRACE_CALL();
2544
Mathias Agopian65ab4712010-07-14 17:59:35 -07002545 LOG1("playSound(%d)", kind);
2546 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002547 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002548 sp<MediaPlayer> player = mSoundPlayer[kind];
2549 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08002550 player->seekTo(0);
2551 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002552 }
2553}
2554
2555// ----------------------------------------------------------------------------
2556
2557CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002558 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002559 const String16& clientPackageName,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002560 const std::unique_ptr<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002561 const String8& cameraIdStr,
2562 int api1CameraId, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002563 int clientPid, uid_t clientUid,
2564 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002565 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08002566 IInterface::asBinder(cameraClient),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002567 clientPackageName, clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002568 cameraIdStr, cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002569 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002570 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002571 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08002572{
Jayant Chowdhary12361932018-08-27 14:46:13 -07002573 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002574 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002575
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002576 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002577
username5755fea2018-12-27 09:48:08 +08002578 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002579
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002580 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002581}
2582
Mathias Agopian65ab4712010-07-14 17:59:35 -07002583// tear down the client
2584CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002585 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08002586 mDestructionStarted = true;
2587
username5755fea2018-12-27 09:48:08 +08002588 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002589 // unconditionally disconnect. function is idempotent
2590 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002591}
2592
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002593sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
2594
Igor Murashkin634a5152013-02-20 17:15:11 -08002595CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002596 const sp<IBinder>& remoteCallback,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002597 const String16& clientPackageName, const std::unique_ptr<String16>& clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002598 const String8& cameraIdStr, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002599 int clientPid, uid_t clientUid,
2600 int servicePid):
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002601 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002602 mClientPackageName(clientPackageName),
2603 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002604 mServicePid(servicePid),
2605 mDisconnected(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002606 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002607 mRemoteBinder(remoteCallback)
Igor Murashkin634a5152013-02-20 17:15:11 -08002608{
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002609 if (clientFeatureId) {
2610 mClientFeatureId = std::unique_ptr<String16>(new String16(*clientFeatureId));
2611 } else {
2612 mClientFeatureId = std::unique_ptr<String16>();
2613 }
2614
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002615 if (sCameraService == nullptr) {
2616 sCameraService = cameraService;
2617 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002618 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08002619 mDestructionStarted = false;
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08002620
2621 // In some cases the calling code has no access to the package it runs under.
2622 // For example, NDK camera API.
2623 // In this case we will get the packages for the calling UID and pick the first one
2624 // for attributing the app op. This will work correctly for runtime permissions
2625 // as for legacy apps we will toggle the app op for all packages in the UID.
2626 // The caveat is that the operation may be attributed to the wrong package and
2627 // stats based on app ops may be slightly off.
2628 if (mClientPackageName.size() <= 0) {
2629 sp<IServiceManager> sm = defaultServiceManager();
2630 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2631 if (binder == 0) {
2632 ALOGE("Cannot get permission service");
2633 // Leave mClientPackageName unchanged (empty) and the further interaction
2634 // with camera will fail in BasicClient::startCameraOps
2635 return;
2636 }
2637
2638 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2639 Vector<String16> packages;
2640
2641 permCtrl->getPackagesForUid(mClientUid, packages);
2642
2643 if (packages.isEmpty()) {
2644 ALOGE("No packages for calling UID");
2645 // Leave mClientPackageName unchanged (empty) and the further interaction
2646 // with camera will fail in BasicClient::startCameraOps
2647 return;
2648 }
2649 mClientPackageName = packages[0];
2650 }
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002651 if (!hardware::IPCThreadState::self()->isServingCall()) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002652 mAppOpsManager = std::make_unique<AppOpsManager>();
2653 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002654}
2655
2656CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002657 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08002658 mDestructionStarted = true;
2659}
2660
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002661binder::Status CameraService::BasicClient::disconnect() {
2662 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002663 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002664 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07002665 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002666 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002667
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002668 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002669 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07002670 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
2671 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002672
2673 sp<IBinder> remote = getRemote();
2674 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002675 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08002676 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002677
2678 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07002679 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002680 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
2681 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
2682 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002683
Igor Murashkincba2c162013-03-20 15:56:31 -07002684 // client shouldn't be able to call into us anymore
2685 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002686
2687 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08002688}
2689
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002690status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2691 // No dumping of clients directly over Binder,
2692 // must go through CameraService::dump
2693 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002694 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002695 return OK;
2696}
2697
Ruben Brunkcc776712015-02-17 20:18:47 -08002698String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002699 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08002700}
2701
2702
2703int CameraService::BasicClient::getClientPid() const {
2704 return mClientPid;
2705}
2706
Ruben Brunk6267b532015-04-30 17:44:07 -07002707uid_t CameraService::BasicClient::getClientUid() const {
2708 return mClientUid;
2709}
2710
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002711bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2712 // Defaults to API2.
2713 return level == API_2;
2714}
2715
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002716status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002717 {
2718 Mutex::Autolock l(mAudioRestrictionLock);
2719 mAudioRestriction = mode;
2720 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002721 sCameraService->updateAudioRestriction();
2722 return OK;
2723}
2724
2725int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002726 return sCameraService->updateAudioRestriction();
2727}
2728
2729int32_t CameraService::BasicClient::getAudioRestriction() const {
2730 Mutex::Autolock l(mAudioRestrictionLock);
2731 return mAudioRestriction;
2732}
2733
2734bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
2735 switch (mode) {
2736 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
2737 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
2738 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
2739 return true;
2740 default:
2741 return false;
2742 }
2743}
2744
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002745status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002746 ATRACE_CALL();
2747
Igor Murashkine6800ce2013-03-04 17:25:57 -08002748 {
2749 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002750 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002751 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002752 if (mAppOpsManager != nullptr) {
2753 // Notify app ops that the camera is not available
2754 mOpsCallback = new OpsCallback(this);
2755 int32_t res;
2756 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
2757 mClientPackageName, mOpsCallback);
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002758 res = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
2759 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
2760 String16("start camera ") + String16(mCameraIdStr));
Igor Murashkine6800ce2013-03-04 17:25:57 -08002761
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002762 if (res == AppOpsManager::MODE_ERRORED) {
2763 ALOGI("Camera %s: Access for \"%s\" has been revoked",
2764 mCameraIdStr.string(), String8(mClientPackageName).string());
2765 return PERMISSION_DENIED;
2766 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002767
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002768 if (res == AppOpsManager::MODE_IGNORED) {
2769 ALOGI("Camera %s: Access for \"%s\" has been restricted",
2770 mCameraIdStr.string(), String8(mClientPackageName).string());
2771 // Return the same error as for device policy manager rejection
2772 return -EACCES;
2773 }
Svetoslav28e8ef72015-05-11 19:21:31 -07002774 }
2775
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002776 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002777
2778 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002779 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002780
Emilian Peev573291c2018-02-10 02:10:56 +00002781 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2782 if (canCastToApiClient(API_2)) {
2783 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2784 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002785 // Transition device state to OPEN
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002786 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
Emilian Peev573291c2018-02-10 02:10:56 +00002787 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002788
Emilian Peev53722fa2019-02-22 17:47:20 -08002789 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
2790
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002791 return OK;
2792}
2793
2794status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002795 ATRACE_CALL();
2796
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002797 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002798 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002799 // Notify app ops that the camera is available again
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002800 if (mAppOpsManager != nullptr) {
2801 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002802 mClientPackageName, mClientFeatureId);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002803 mOpsActive = false;
2804 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002805 // This function is called when a client disconnects. This should
2806 // release the camera, but actually only if it was in a proper
2807 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002808 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002809 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002810
Ruben Brunkcc776712015-02-17 20:18:47 -08002811 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002812 sCameraService->updateStatus(StatusInternal::PRESENT,
2813 mCameraIdStr, rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002814
Emilian Peev573291c2018-02-10 02:10:56 +00002815 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2816 if (canCastToApiClient(API_2)) {
2817 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2818 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002819 // Transition device state to CLOSED
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002820 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
Emilian Peev573291c2018-02-10 02:10:56 +00002821 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002822 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002823 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002824 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
2825 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002826 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002827 mOpsCallback.clear();
2828
Emilian Peev53722fa2019-02-22 17:47:20 -08002829 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
2830
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002831 return OK;
2832}
2833
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002834void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002835 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002836 if (mAppOpsManager == nullptr) {
2837 return;
2838 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002839 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002840 if (op != AppOpsManager::OP_CAMERA) {
2841 ALOGW("Unexpected app ops notification received: %d", op);
2842 return;
2843 }
2844
2845 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002846 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002847 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002848 ALOGV("checkOp returns: %d, %s ", res,
2849 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
2850 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
2851 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
2852 "UNKNOWN");
2853
2854 if (res != AppOpsManager::MODE_ALLOWED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002855 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002856 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08002857 block();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002858 }
2859}
2860
Svet Ganova453d0d2018-01-11 15:37:58 -08002861void CameraService::BasicClient::block() {
2862 ATRACE_CALL();
2863
2864 // Reset the client PID to allow server-initiated disconnect,
2865 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07002866 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08002867 CaptureResultExtras resultExtras; // a dummy result (invalid)
2868 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
2869 disconnect();
2870}
2871
Mathias Agopian65ab4712010-07-14 17:59:35 -07002872// ----------------------------------------------------------------------------
2873
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002874void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07002875 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002876 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07002877 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07002878 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
2879 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
2880 api1ErrorCode = CAMERA_ERROR_DISABLED;
2881 }
2882 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07002883 } else {
2884 ALOGE("mRemoteCallback is NULL!!");
2885 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002886}
2887
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002888// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002889binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002890 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002891 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08002892}
2893
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002894bool CameraService::Client::canCastToApiClient(apiLevel level) const {
2895 return level == API_1;
2896}
2897
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002898CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
2899 mClient(client) {
2900}
2901
2902void CameraService::Client::OpsCallback::opChanged(int32_t op,
2903 const String16& packageName) {
2904 sp<BasicClient> client = mClient.promote();
2905 if (client != NULL) {
2906 client->opChanged(op, packageName);
2907 }
2908}
2909
Mathias Agopian65ab4712010-07-14 17:59:35 -07002910// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08002911// UidPolicy
2912// ----------------------------------------------------------------------------
2913
2914void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002915 Mutex::Autolock _l(mUidLock);
2916
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002917 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07002918 status_t res = mAm.linkToDeath(this);
2919 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08002920 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08002921 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08002922 ActivityManager::PROCESS_STATE_UNKNOWN,
2923 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002924 if (res == OK) {
2925 mRegistered = true;
2926 ALOGV("UidPolicy: Registered with ActivityManager");
2927 }
Svet Ganova453d0d2018-01-11 15:37:58 -08002928}
2929
2930void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002931 Mutex::Autolock _l(mUidLock);
2932
Steven Moreland2f348142019-07-02 15:59:07 -07002933 mAm.unregisterUidObserver(this);
2934 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002935 mRegistered = false;
2936 mActiveUids.clear();
2937 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08002938}
2939
2940void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
2941 onUidIdle(uid, disabled);
2942}
2943
2944void CameraService::UidPolicy::onUidActive(uid_t uid) {
2945 Mutex::Autolock _l(mUidLock);
2946 mActiveUids.insert(uid);
2947}
2948
2949void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
2950 bool deleted = false;
2951 {
2952 Mutex::Autolock _l(mUidLock);
2953 if (mActiveUids.erase(uid) > 0) {
2954 deleted = true;
2955 }
2956 }
2957 if (deleted) {
2958 sp<CameraService> service = mService.promote();
2959 if (service != nullptr) {
2960 service->blockClientsForUid(uid);
2961 }
2962 }
2963}
2964
Emilian Peev53722fa2019-02-22 17:47:20 -08002965void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07002966 int64_t procStateSeq __unused, int32_t capability __unused) {
Emilian Peev53722fa2019-02-22 17:47:20 -08002967 bool procStateChange = false;
2968 {
2969 Mutex::Autolock _l(mUidLock);
2970 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
2971 (mMonitoredUids[uid].first != procState)) {
2972 mMonitoredUids[uid].first = procState;
2973 procStateChange = true;
2974 }
2975 }
2976
2977 if (procStateChange) {
2978 sp<CameraService> service = mService.promote();
2979 if (service != nullptr) {
2980 service->notifyMonitoredUids();
2981 }
2982 }
2983}
2984
2985void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
2986 Mutex::Autolock _l(mUidLock);
2987 auto it = mMonitoredUids.find(uid);
2988 if (it != mMonitoredUids.end()) {
2989 it->second.second++;
2990 } else {
2991 mMonitoredUids.emplace(
2992 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
2993 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
2994 }
2995}
2996
2997void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
2998 Mutex::Autolock _l(mUidLock);
2999 auto it = mMonitoredUids.find(uid);
3000 if (it != mMonitoredUids.end()) {
3001 it->second.second--;
3002 if (it->second.second == 0) {
3003 mMonitoredUids.erase(it);
3004 }
3005 } else {
3006 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3007 }
3008}
3009
Svet Ganov7b4ab782018-03-25 12:48:10 -07003010bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003011 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003012 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003013}
3014
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003015static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3016static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003017
Svet Ganov7b4ab782018-03-25 12:48:10 -07003018bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003019 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003020 // If activity manager is unreachable, assume everything is active
3021 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003022 return true;
3023 }
3024 auto it = mOverrideUids.find(uid);
3025 if (it != mOverrideUids.end()) {
3026 return it->second;
3027 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003028 bool active = mActiveUids.find(uid) != mActiveUids.end();
3029 if (!active) {
3030 // We want active UIDs to always access camera with their first attempt since
3031 // there is no guarantee the app is robustly written and would retry getting
3032 // the camera on failure. The inverse case is not a problem as we would take
3033 // camera away soon once we get the callback that the uid is no longer active.
3034 ActivityManager am;
3035 // Okay to access with a lock held as UID changes are dispatched without
3036 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003037 int64_t startTimeMillis = 0;
3038 do {
3039 // TODO: Fix this b/109950150!
3040 // Okay this is a hack. There is a race between the UID turning active and
3041 // activity being resumed. The proper fix is very risky, so we temporary add
3042 // some polling which should happen pretty rarely anyway as the race is hard
3043 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003044 active = mActiveUids.find(uid) != mActiveUids.end();
3045 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003046 if (active) {
3047 break;
3048 }
3049 if (startTimeMillis <= 0) {
3050 startTimeMillis = uptimeMillis();
3051 }
3052 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003053 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003054 if (remainingTimeMillis <= 0) {
3055 break;
3056 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003057 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3058
3059 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003060 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003061 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003062 } while (true);
3063
Svet Ganov7b4ab782018-03-25 12:48:10 -07003064 if (active) {
3065 // Now that we found out the UID is actually active, cache that
3066 mActiveUids.insert(uid);
3067 }
3068 }
3069 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08003070}
3071
Varun Shahb42f1eb2019-04-16 14:45:13 -07003072int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3073 Mutex::Autolock _l(mUidLock);
3074 return getProcStateLocked(uid);
3075}
3076
3077int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3078 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3079 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3080 procState = mMonitoredUids[uid].first;
3081 }
3082 return procState;
3083}
3084
Svet Ganov7b4ab782018-03-25 12:48:10 -07003085void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3086 String16 callingPackage, bool active) {
3087 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003088}
3089
Svet Ganov7b4ab782018-03-25 12:48:10 -07003090void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3091 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003092}
3093
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003094void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3095 Mutex::Autolock _l(mUidLock);
3096 ALOGV("UidPolicy: ActivityManager has died");
3097 mRegistered = false;
3098 mActiveUids.clear();
3099}
3100
Svet Ganov7b4ab782018-03-25 12:48:10 -07003101void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3102 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003103 bool wasActive = false;
3104 bool isActive = false;
3105 {
3106 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003107 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003108 mOverrideUids.erase(uid);
3109 if (insert) {
3110 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3111 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003112 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003113 }
3114 if (wasActive != isActive && !isActive) {
3115 sp<CameraService> service = mService.promote();
3116 if (service != nullptr) {
3117 service->blockClientsForUid(uid);
3118 }
3119 }
3120}
3121
3122// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08003123// SensorPrivacyPolicy
3124// ----------------------------------------------------------------------------
3125void CameraService::SensorPrivacyPolicy::registerSelf() {
3126 Mutex::Autolock _l(mSensorPrivacyLock);
3127 if (mRegistered) {
3128 return;
3129 }
3130 SensorPrivacyManager spm;
3131 spm.addSensorPrivacyListener(this);
3132 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
3133 status_t res = spm.linkToDeath(this);
3134 if (res == OK) {
3135 mRegistered = true;
3136 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3137 }
3138}
3139
3140void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3141 Mutex::Autolock _l(mSensorPrivacyLock);
3142 SensorPrivacyManager spm;
3143 spm.removeSensorPrivacyListener(this);
3144 spm.unlinkToDeath(this);
3145 mRegistered = false;
3146 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3147}
3148
3149bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3150 Mutex::Autolock _l(mSensorPrivacyLock);
3151 return mSensorPrivacyEnabled;
3152}
3153
3154binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3155 {
3156 Mutex::Autolock _l(mSensorPrivacyLock);
3157 mSensorPrivacyEnabled = enabled;
3158 }
3159 // if sensor privacy is enabled then block all clients from accessing the camera
3160 if (enabled) {
3161 sp<CameraService> service = mService.promote();
3162 if (service != nullptr) {
3163 service->blockAllClients();
3164 }
3165 }
3166 return binder::Status::ok();
3167}
3168
3169void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3170 Mutex::Autolock _l(mSensorPrivacyLock);
3171 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3172 mRegistered = false;
3173}
3174
3175// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003176// CameraState
3177// ----------------------------------------------------------------------------
3178
3179CameraService::CameraState::CameraState(const String8& id, int cost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003180 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind) : mId(id),
3181 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
3182 mSystemCameraKind(systemCameraKind) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003183
3184CameraService::CameraState::~CameraState() {}
3185
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003186CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003187 Mutex::Autolock lock(mStatusLock);
3188 return mStatus;
3189}
3190
3191CameraParameters CameraService::CameraState::getShimParams() const {
3192 return mShimParams;
3193}
3194
3195void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3196 mShimParams = params;
3197}
3198
3199int CameraService::CameraState::getCost() const {
3200 return mCost;
3201}
3202
3203std::set<String8> CameraService::CameraState::getConflicting() const {
3204 return mConflicting;
3205}
3206
3207String8 CameraService::CameraState::getId() const {
3208 return mId;
3209}
3210
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003211SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3212 return mSystemCameraKind;
3213}
3214
Ruben Brunkcc776712015-02-17 20:18:47 -08003215// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07003216// ClientEventListener
3217// ----------------------------------------------------------------------------
3218
3219void CameraService::ClientEventListener::onClientAdded(
3220 const resource_policy::ClientDescriptor<String8,
3221 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003222 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003223 if (basicClient.get() != nullptr) {
3224 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3225 notifier.noteStartCamera(descriptor.getKey(),
3226 static_cast<int>(basicClient->getClientUid()));
3227 }
3228}
3229
3230void CameraService::ClientEventListener::onClientRemoved(
3231 const resource_policy::ClientDescriptor<String8,
3232 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003233 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003234 if (basicClient.get() != nullptr) {
3235 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3236 notifier.noteStopCamera(descriptor.getKey(),
3237 static_cast<int>(basicClient->getClientUid()));
3238 }
3239}
3240
3241
3242// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003243// CameraClientManager
3244// ----------------------------------------------------------------------------
3245
Ruben Brunk99e69712015-05-26 17:25:07 -07003246CameraService::CameraClientManager::CameraClientManager() {
3247 setListener(std::make_shared<ClientEventListener>());
3248}
3249
Ruben Brunkcc776712015-02-17 20:18:47 -08003250CameraService::CameraClientManager::~CameraClientManager() {}
3251
3252sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
3253 const String8& id) const {
3254 auto descriptor = get(id);
3255 if (descriptor == nullptr) {
3256 return sp<BasicClient>{nullptr};
3257 }
3258 return descriptor->getValue();
3259}
3260
3261String8 CameraService::CameraClientManager::toString() const {
3262 auto all = getAll();
3263 String8 ret("[");
3264 bool hasAny = false;
3265 for (auto& i : all) {
3266 hasAny = true;
3267 String8 key = i->getKey();
3268 int32_t cost = i->getCost();
3269 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00003270 int32_t score = i->getPriority().getScore();
3271 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08003272 auto conflicting = i->getConflicting();
3273 auto clientSp = i->getValue();
3274 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07003275 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08003276 if (clientSp.get() != nullptr) {
3277 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07003278 uid_t clientUid = clientSp->getClientUid();
3279 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003280 }
Emilian Peev8131a262017-02-01 12:33:43 +00003281 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
3282 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08003283
Ruben Brunk6267b532015-04-30 17:44:07 -07003284 if (clientSp.get() != nullptr) {
3285 ret.appendFormat("User Id: %d, ", clientUserId);
3286 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003287 if (packageName.size() != 0) {
3288 ret.appendFormat("Client Package Name: %s", packageName.string());
3289 }
3290
3291 ret.append(", Conflicting Client Devices: {");
3292 for (auto& j : conflicting) {
3293 ret.appendFormat("%s, ", j.string());
3294 }
3295 ret.append("})");
3296 }
3297 if (hasAny) ret.append("\n");
3298 ret.append("]\n");
3299 return ret;
3300}
3301
3302CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3303 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00003304 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
3305 int32_t state) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003306
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003307 bool isVendorClient = hardware::IPCThreadState::self()->isServingCall();
3308 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
3309 int32_t state_adj = isVendorClient ? kVendorClientState: state;
3310
Ruben Brunkcc776712015-02-17 20:18:47 -08003311 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003312 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08003313}
3314
3315CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3316 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
3317 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00003318 partial->getConflicting(), partial->getPriority().getScore(),
3319 partial->getOwnerId(), partial->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08003320}
3321
3322// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07003323
3324static const int kDumpLockRetries = 50;
3325static const int kDumpLockSleep = 60000;
3326
3327static bool tryLock(Mutex& mutex)
3328{
3329 bool locked = false;
3330 for (int i = 0; i < kDumpLockRetries; ++i) {
3331 if (mutex.tryLock() == NO_ERROR) {
3332 locked = true;
3333 break;
3334 }
3335 usleep(kDumpLockSleep);
3336 }
3337 return locked;
3338}
3339
3340status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003341 ATRACE_CALL();
3342
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003343 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003344 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003345 CameraThreadState::getCallingPid(),
3346 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003347 return NO_ERROR;
3348 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003349 bool locked = tryLock(mServiceLock);
3350 // failed to lock - CameraService is probably deadlocked
3351 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003352 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003353 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003354
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003355 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003356 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07003357
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003358 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003359 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08003360
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003361 if (locked) mServiceLock.unlock();
3362 return NO_ERROR;
3363 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003364 dprintf(fd, "\n== Service global info: ==\n\n");
3365 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003366 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07003367 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
3368 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003369 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
3370 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
3371 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003372 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003373 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
3374 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003375
3376 dumpEventLog(fd);
3377
3378 bool stateLocked = tryLock(mCameraStatesLock);
3379 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003380 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003381 }
3382
Emilian Peevbd8c5032018-02-14 23:05:40 +00003383 int argSize = args.size();
3384 for (int i = 0; i < argSize; i++) {
3385 if (args[i] == TagMonitor::kMonitorOption) {
3386 if (i + 1 < argSize) {
3387 mMonitorTags = String8(args[i + 1]);
3388 }
3389 break;
3390 }
3391 }
3392
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003393 for (auto& state : mCameraStates) {
3394 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003395
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003396 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003397
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003398 CameraParameters p = state.second->getShimParams();
3399 if (!p.isEmpty()) {
3400 dprintf(fd, " Camera1 API shim is using parameters:\n ");
3401 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003402 }
3403
3404 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08003405 if (clientDescriptor != nullptr) {
3406 dprintf(fd, " Device %s is open. Client instance dump:\n",
3407 cameraId.string());
3408 dprintf(fd, " Client priority score: %d state: %d\n",
3409 clientDescriptor->getPriority().getScore(),
3410 clientDescriptor->getPriority().getState());
3411 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
3412
3413 auto client = clientDescriptor->getValue();
3414 dprintf(fd, " Client package: %s\n",
3415 String8(client->getPackageName()).string());
3416
3417 client->dumpClient(fd, args);
3418 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003419 dprintf(fd, " Device %s is closed, no client instance\n",
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003420 cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003421 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003422
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003423 }
3424
3425 if (stateLocked) mCameraStatesLock.unlock();
3426
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003427 if (locked) mServiceLock.unlock();
3428
Emilian Peevf53f66e2017-04-11 14:29:43 +01003429 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003430
3431 dprintf(fd, "\n== Vendor tags: ==\n\n");
3432
3433 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
3434 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00003435 sp<VendorTagDescriptorCache> cache =
3436 VendorTagDescriptorCache::getGlobalVendorTagCache();
3437 if (cache == NULL) {
3438 dprintf(fd, "No vendor tags.\n");
3439 } else {
3440 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
3441 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003442 } else {
3443 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
3444 }
3445
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003446 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003447 dprintf(fd, "\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003448 camera3::CameraTraces::dump(fd, args);
3449
3450 // Process dump arguments, if any
3451 int n = args.size();
3452 String16 verboseOption("-v");
3453 String16 unreachableOption("--unreachable");
3454 for (int i = 0; i < n; i++) {
3455 if (args[i] == verboseOption) {
3456 // change logging level
3457 if (i + 1 >= n) continue;
3458 String8 levelStr(args[i+1]);
3459 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003460 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003461 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003462 } else if (args[i] == unreachableOption) {
3463 // Dump memory analysis
3464 // TODO - should limit be an argument parameter?
3465 UnreachableMemoryInfo info;
3466 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
3467 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003468 dprintf(fd, "\n== Unable to dump unreachable memory. "
3469 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003470 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003471 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003472 std::string s = info.ToString(/*log_contents*/ true);
3473 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003474 }
3475 }
3476 }
3477 return NO_ERROR;
3478}
3479
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003480void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003481 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003482
3483 Mutex::Autolock l(mLogLock);
3484 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003485 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003486 }
3487
3488 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003489 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003490 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003491 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003492 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003493 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003494}
3495
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003496void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003497 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003498 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
3499 if (mTorchClientMap[i] == who) {
3500 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003501 String8 cameraId = mTorchClientMap.keyAt(i);
3502 status_t res = mFlashlight->setTorchMode(cameraId, false);
3503 if (res) {
3504 ALOGE("%s: torch client died but couldn't turn off torch: "
3505 "%s (%d)", __FUNCTION__, strerror(-res), res);
3506 return;
3507 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003508 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003509 break;
3510 }
3511 }
3512}
3513
Ruben Brunkcc776712015-02-17 20:18:47 -08003514/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003515
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003516 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07003517 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
3518 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003519 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003520 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003521 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003522
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003523 // check torch client
3524 handleTorchClientBinderDied(who);
3525
3526 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08003527 if(!evictClientIdByRemote(who)) {
3528 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003529 return;
3530 }
3531
Ruben Brunkcc776712015-02-17 20:18:47 -08003532 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
3533 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003534}
3535
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003536void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003537 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08003538}
3539
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003540void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
3541 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003542 // Do not lock mServiceLock here or can get into a deadlock from
3543 // connect() -> disconnect -> updateStatus
3544
3545 auto state = getCameraState(cameraId);
3546
3547 if (state == nullptr) {
3548 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
3549 cameraId.string());
3550 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07003551 }
3552
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003553 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
3554 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3555 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3556 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
3557 return;
3558 }
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003559 bool supportsHAL3 = false;
3560 // supportsCameraApi also holds mInterfaceMutex, we can't call it in the
3561 // HIDL onStatusChanged wrapper call (we'll hold mStatusListenerLock and
3562 // mInterfaceMutex together, which can lead to deadlocks)
3563 binder::Status sRet =
3564 supportsCameraApi(String16(cameraId), hardware::ICameraService::API_VERSION_2,
3565 &supportsHAL3);
3566 if (!sRet.isOk()) {
3567 ALOGW("%s: Failed to determine if device supports HAL3 %s, supportsCameraApi call failed",
3568 __FUNCTION__, cameraId.string());
3569 return;
3570 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003571 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
3572 // of the listeners with both the mStatusStatus and mStatusListenerLock held
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003573 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind, &supportsHAL3]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003574 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003575
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003576 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003577 // Update torch status if it has a flash unit.
3578 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003579 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003580 if (getTorchStatusLocked(cameraId, &torchStatus) !=
3581 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003582 TorchModeStatus newTorchStatus =
3583 status == StatusInternal::PRESENT ?
3584 TorchModeStatus::AVAILABLE_OFF :
3585 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003586 if (torchStatus != newTorchStatus) {
3587 onTorchStatusChangedLocked(cameraId, newTorchStatus);
3588 }
3589 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003590 }
3591
3592 Mutex::Autolock lock(mStatusListenerLock);
3593
3594 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003595 bool isVendorListener = listener->isVendorListener();
3596 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
3597 listener->getListenerPid(), listener->getListenerUid()) ||
3598 (isVendorListener && !supportsHAL3)) {
3599 ALOGV("Skipping discovery callback for system-only camera/HAL1 device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003600 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003601 continue;
3602 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003603 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08003604 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08003605 }
3606 });
Igor Murashkincba2c162013-03-20 15:56:31 -07003607}
3608
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003609template<class Func>
3610void CameraService::CameraState::updateStatus(StatusInternal status,
3611 const String8& cameraId,
3612 std::initializer_list<StatusInternal> rejectSourceStates,
3613 Func onStatusUpdatedLocked) {
3614 Mutex::Autolock lock(mStatusLock);
3615 StatusInternal oldStatus = mStatus;
3616 mStatus = status;
3617
3618 if (oldStatus == status) {
3619 return;
3620 }
3621
3622 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
3623 cameraId.string(), oldStatus, status);
3624
3625 if (oldStatus == StatusInternal::NOT_PRESENT &&
3626 (status != StatusInternal::PRESENT &&
3627 status != StatusInternal::ENUMERATING)) {
3628
3629 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
3630 __FUNCTION__);
3631 mStatus = oldStatus;
3632 return;
3633 }
3634
3635 /**
3636 * Sometimes we want to conditionally do a transition.
3637 * For example if a client disconnects, we want to go to PRESENT
3638 * only if we weren't already in NOT_PRESENT or ENUMERATING.
3639 */
3640 for (auto& rejectStatus : rejectSourceStates) {
3641 if (oldStatus == rejectStatus) {
3642 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
3643 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
3644 mStatus = oldStatus;
3645 return;
3646 }
3647 }
3648
3649 onStatusUpdatedLocked(cameraId, status);
3650}
3651
Eino-Ville Talvalae8c96c72017-06-27 12:24:07 -07003652void CameraService::updateProxyDeviceState(int newState,
Emilian Peev573291c2018-02-10 02:10:56 +00003653 const String8& cameraId, int facing, const String16& clientName, int apiLevel) {
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003654 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
3655 if (proxyBinder == nullptr) return;
3656 String16 id(cameraId);
Emilian Peev573291c2018-02-10 02:10:56 +00003657 proxyBinder->notifyCameraState(id, newState, facing, clientName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003658}
3659
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003660status_t CameraService::getTorchStatusLocked(
3661 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003662 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003663 if (!status) {
3664 return BAD_VALUE;
3665 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003666 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3667 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003668 // invalid camera ID or the camera doesn't have a flash unit
3669 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003670 }
3671
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003672 *status = mTorchStatusMap.valueAt(index);
3673 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003674}
3675
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003676status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003677 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003678 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3679 if (index == NAME_NOT_FOUND) {
3680 return BAD_VALUE;
3681 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003682 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003683
3684 return OK;
3685}
3686
Svet Ganova453d0d2018-01-11 15:37:58 -08003687void CameraService::blockClientsForUid(uid_t uid) {
3688 const auto clients = mActiveClientManager.getAll();
3689 for (auto& current : clients) {
3690 if (current != nullptr) {
3691 const auto basicClient = current->getValue();
3692 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
3693 basicClient->block();
3694 }
3695 }
3696 }
3697}
3698
Michael Grooverd1d435a2018-12-18 17:39:42 -08003699void CameraService::blockAllClients() {
3700 const auto clients = mActiveClientManager.getAll();
3701 for (auto& current : clients) {
3702 if (current != nullptr) {
3703 const auto basicClient = current->getValue();
3704 if (basicClient.get() != nullptr) {
3705 basicClient->block();
3706 }
3707 }
3708 }
3709}
3710
Svet Ganova453d0d2018-01-11 15:37:58 -08003711// NOTE: This is a remote API - make sure all args are validated
3712status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
3713 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
3714 return PERMISSION_DENIED;
3715 }
3716 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
3717 return BAD_VALUE;
3718 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003719 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003720 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003721 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003722 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003723 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003724 return handleGetUidState(args, out, err);
3725 } else if (args.size() == 1 && args[0] == String16("help")) {
3726 printHelp(out);
3727 return NO_ERROR;
3728 }
3729 printHelp(err);
3730 return BAD_VALUE;
3731}
3732
3733status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003734 String16 packageName = args[1];
3735
Svet Ganova453d0d2018-01-11 15:37:58 -08003736 bool active = false;
3737 if (args[2] == String16("active")) {
3738 active = true;
3739 } else if ((args[2] != String16("idle"))) {
3740 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
3741 return BAD_VALUE;
3742 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003743
3744 int userId = 0;
3745 if (args.size() >= 5 && args[3] == String16("--user")) {
3746 userId = atoi(String8(args[4]));
3747 }
3748
3749 uid_t uid;
3750 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
3751 return BAD_VALUE;
3752 }
3753
3754 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08003755 return NO_ERROR;
3756}
3757
3758status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003759 String16 packageName = args[1];
3760
3761 int userId = 0;
3762 if (args.size() >= 4 && args[2] == String16("--user")) {
3763 userId = atoi(String8(args[3]));
3764 }
3765
3766 uid_t uid;
3767 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003768 return BAD_VALUE;
3769 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003770
3771 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08003772 return NO_ERROR;
3773}
3774
3775status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003776 String16 packageName = args[1];
3777
3778 int userId = 0;
3779 if (args.size() >= 4 && args[2] == String16("--user")) {
3780 userId = atoi(String8(args[3]));
3781 }
3782
3783 uid_t uid;
3784 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003785 return BAD_VALUE;
3786 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003787
3788 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003789 return dprintf(out, "active\n");
3790 } else {
3791 return dprintf(out, "idle\n");
3792 }
3793}
3794
3795status_t CameraService::printHelp(int out) {
3796 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07003797 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
3798 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
3799 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08003800 " help print this message\n");
3801}
3802
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003803int32_t CameraService::updateAudioRestriction() {
3804 Mutex::Autolock lock(mServiceLock);
3805 return updateAudioRestrictionLocked();
3806}
3807
3808int32_t CameraService::updateAudioRestrictionLocked() {
3809 int32_t mode = 0;
3810 // iterate through all active client
3811 for (const auto& i : mActiveClientManager.getAll()) {
3812 const auto clientSp = i->getValue();
3813 mode |= clientSp->getAudioRestriction();
3814 }
3815
3816 bool modeChanged = (mAudioRestriction != mode);
3817 mAudioRestriction = mode;
3818 if (modeChanged) {
3819 mAppOps.setCameraAudioRestriction(mode);
3820 }
3821 return mode;
3822}
3823
Mathias Agopian65ab4712010-07-14 17:59:35 -07003824}; // namespace android