blob: 94642f2a8df5317d91523a0d1c5f41a6e3034f78 [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
Ruben Brunkd1176ef2014-02-21 10:51:38 -08002 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Mathias Agopian65ab4712010-07-14 17:59:35 -070016
17#define LOG_TAG "CameraService"
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -070018#define ATRACE_TAG ATRACE_TAG_CAMERA
Iliyan Malchev8951a972011-04-14 16:55:59 -070019//#define LOG_NDEBUG 0
Mathias Agopian65ab4712010-07-14 17:59:35 -070020
Ruben Brunkcc776712015-02-17 20:18:47 -080021#include <algorithm>
22#include <climits>
Mathias Agopian65ab4712010-07-14 17:59:35 -070023#include <stdio.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080024#include <cstring>
25#include <ctime>
26#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070027#include <sys/types.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080028#include <inttypes.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070029#include <pthread.h>
30
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080031#include <android/hardware/ICamera.h>
32#include <android/hardware/ICameraClient.h>
33
Alex Deymo9c2a2c22016-08-25 11:59:14 -070034#include <android-base/macros.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080035#include <android-base/parseint.h>
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070036#include <android-base/stringprintf.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080037#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080038#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070039#include <binder/IPCThreadState.h>
40#include <binder/IServiceManager.h>
41#include <binder/MemoryBase.h>
42#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080043#include <binder/PermissionController.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080044#include <binder/ProcessInfoService.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080045#include <binder/IResultReceiver.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070046#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070047#include <cutils/properties.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080048#include <cutils/misc.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080049#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070050#include <hardware/hardware.h>
Jayant Chowdharybe543d42018-08-15 13:16:14 -070051#include "hidl/HidlCameraService.h"
52#include <hidl/HidlTransportSupport.h>
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -080053#include <hwbinder/IPCThreadState.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070054#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070055#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080056#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070057#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070058#include <mediautils/BatteryNotifier.h>
Michael Grooverd1d435a2018-12-18 17:39:42 -080059#include <sensorprivacy/SensorPrivacyManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070060#include <utils/Errors.h>
61#include <utils/Log.h>
62#include <utils/String16.h>
Svet Ganov94ec46f2018-06-08 15:03:46 -070063#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080064#include <utils/Trace.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080065#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080066#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070067#include <system/camera_metadata.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080068
Ruben Brunkb2119af2014-05-09 19:57:56 -070069#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070070
71#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070072#include "api1/CameraClient.h"
73#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070074#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070075#include "utils/CameraTraces.h"
Emilian Peevbd8c5032018-02-14 23:05:40 +000076#include "utils/TagMonitor.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070077#include "utils/CameraThreadState.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070078
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080079namespace {
80 const char* kPermissionServiceName = "permission";
81}; // namespace anonymous
82
Mathias Agopian65ab4712010-07-14 17:59:35 -070083namespace android {
84
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070085using base::StringPrintf;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080086using binder::Status;
Jayant Chowdharybe543d42018-08-15 13:16:14 -070087using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -080088using hardware::ICamera;
89using hardware::ICameraClient;
Eino-Ville Talvalae8c96c72017-06-27 12:24:07 -070090using hardware::ICameraServiceProxy;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -080091using hardware::ICameraServiceListener;
92using hardware::camera::common::V1_0::CameraDeviceStatus;
93using hardware::camera::common::V1_0::TorchModeStatus;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080094
Mathias Agopian65ab4712010-07-14 17:59:35 -070095// ----------------------------------------------------------------------------
96// Logging support -- this is for debugging only
97// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -070098volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -070099
Steve Blockb8a80522011-12-20 16:23:08 +0000100#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
101#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700102
103static void setLogLevel(int level) {
104 android_atomic_write(level, &gLogLevel);
105}
106
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800107// Convenience methods for constructing binder::Status objects for error returns
108
109#define STATUS_ERROR(errorCode, errorString) \
110 binder::Status::fromServiceSpecificError(errorCode, \
111 String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
112
113#define STATUS_ERROR_FMT(errorCode, errorString, ...) \
114 binder::Status::fromServiceSpecificError(errorCode, \
115 String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, \
116 __VA_ARGS__))
117
Mathias Agopian65ab4712010-07-14 17:59:35 -0700118// ----------------------------------------------------------------------------
119
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700120static const String16 sDumpPermission("android.permission.DUMP");
Svet Ganova453d0d2018-01-11 15:37:58 -0800121static const String16 sManageCameraPermission("android.permission.MANAGE_CAMERA");
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700122static const String16 sCameraPermission("android.permission.CAMERA");
123static const String16 sSystemCameraPermission("android.permission.SYSTEM_CAMERA");
124static const String16
125 sCameraSendSystemEventsPermission("android.permission.CAMERA_SEND_SYSTEM_EVENTS");
Svet Ganova453d0d2018-01-11 15:37:58 -0800126
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700127// Matches with PERCEPTIBLE_APP_ADJ in ProcessList.java
128static constexpr int32_t kVendorClientScore = 200;
129// Matches with PROCESS_STATE_PERSISTENT_UI in ActivityManager.java
130static constexpr int32_t kVendorClientState = 1;
131
Eino-Ville Talvala7d5569f2019-04-08 13:57:54 -0700132Mutex CameraService::sProxyMutex;
133sp<hardware::ICameraServiceProxy> CameraService::sCameraServiceProxy;
134
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800135CameraService::CameraService() :
136 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800137 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700138 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700139 mSoundRef(0), mInitialized(false),
140 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000141 ALOGI("CameraService started (pid=%d)", getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800142 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700143}
144
Iliyan Malchev8951a972011-04-14 16:55:59 -0700145void CameraService::onFirstRef()
146{
Ruben Brunkcc776712015-02-17 20:18:47 -0800147 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800148
Iliyan Malchev8951a972011-04-14 16:55:59 -0700149 BnCameraService::onFirstRef();
150
Ruben Brunk99e69712015-05-26 17:25:07 -0700151 // Update battery life tracking if service is restarting
152 BatteryNotifier& notifier(BatteryNotifier::getInstance());
153 notifier.noteResetCamera();
154 notifier.noteResetFlashlight();
155
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800156 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800157
Emilian Peevf53f66e2017-04-11 14:29:43 +0100158 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800159 if (res == OK) {
160 mInitialized = true;
161 }
162
Svet Ganova453d0d2018-01-11 15:37:58 -0800163 mUidPolicy = new UidPolicy(this);
164 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800165 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
166 mSensorPrivacyPolicy->registerSelf();
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700167 mAppOps.setCameraAudioRestriction(mAudioRestriction);
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700168 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
169 if (hcs->registerAsService() != android::OK) {
170 ALOGE("%s: Failed to register default android.frameworks.cameraservice.service@1.0",
171 __FUNCTION__);
172 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700173
174 // This needs to be last call in this function, so that it's as close to
175 // ServiceManager::addService() as possible.
176 CameraService::pingCameraServiceProxy();
177 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800178}
179
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800180status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800181 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100182
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800183 std::vector<std::string> deviceIds;
184 {
185 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800186
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800187 if (nullptr == mCameraProviderManager.get()) {
188 mCameraProviderManager = new CameraProviderManager();
189 res = mCameraProviderManager->initialize(this);
190 if (res != OK) {
191 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
192 __FUNCTION__, strerror(-res), res);
193 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100194 }
195 }
196
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800197
198 // Setup vendor tags before we call get_camera_info the first time
199 // because HAL might need to setup static vendor keys in get_camera_info
200 // TODO: maybe put this into CameraProviderManager::initialize()?
201 mCameraProviderManager->setUpVendorTags();
202
203 if (nullptr == mFlashlight.get()) {
204 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700205 }
206
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800207 res = mFlashlight->findFlashUnits();
208 if (res != OK) {
209 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
210 }
211
212 deviceIds = mCameraProviderManager->getCameraDeviceIds();
213 }
214
215
216 for (auto& cameraId : deviceIds) {
217 String8 id8 = String8(cameraId.c_str());
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800218 if (getCameraState(id8) == nullptr) {
219 onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
220 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800221 }
222
223 return OK;
224}
225
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700226sp<ICameraServiceProxy> CameraService::getCameraServiceProxy() {
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800227#ifndef __BRILLO__
Eino-Ville Talvala7d5569f2019-04-08 13:57:54 -0700228 Mutex::Autolock al(sProxyMutex);
229 if (sCameraServiceProxy == nullptr) {
230 sp<IServiceManager> sm = defaultServiceManager();
231 // Use checkService because cameraserver normally starts before the
232 // system server and the proxy service. So the long timeout that getService
233 // has before giving up is inappropriate.
234 sp<IBinder> binder = sm->checkService(String16("media.camera.proxy"));
235 if (binder != nullptr) {
236 sCameraServiceProxy = interface_cast<ICameraServiceProxy>(binder);
237 }
Ruben Brunk2823ce02015-05-19 17:25:13 -0700238 }
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800239#endif
Eino-Ville Talvala7d5569f2019-04-08 13:57:54 -0700240 return sCameraServiceProxy;
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700241}
242
243void CameraService::pingCameraServiceProxy() {
244 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
245 if (proxyBinder == nullptr) return;
Ruben Brunk2823ce02015-05-19 17:25:13 -0700246 proxyBinder->pingForUserUpdate();
Iliyan Malchev8951a972011-04-14 16:55:59 -0700247}
248
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800249void CameraService::broadcastTorchModeStatus(const String8& cameraId, TorchModeStatus status) {
250 Mutex::Autolock lock(mStatusListenerLock);
251
252 for (auto& i : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700253 i->getListener()->onTorchStatusChanged(mapToInterface(status), String16{cameraId});
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800254 }
255}
256
Mathias Agopian65ab4712010-07-14 17:59:35 -0700257CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800258 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800259 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800260 mSensorPrivacyPolicy->unregisterSelf();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700261}
262
Emilian Peevaee727d2017-05-04 16:35:48 +0100263void CameraService::onNewProviderRegistered() {
264 enumerateProviders();
265}
266
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700267void CameraService::filterAPI1SystemCameraLocked(
268 const std::vector<std::string> &normalDeviceIds) {
269 mNormalDeviceIdsWithoutSystemCamera.clear();
270 for (auto &deviceId : normalDeviceIds) {
271 if (getSystemCameraKind(String8(deviceId.c_str())) ==
272 SystemCameraKind::SYSTEM_ONLY_CAMERA) {
273 // All system camera ids will necessarily come after public camera
274 // device ids as per the HAL interface contract.
275 break;
276 }
277 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
278 }
279 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
280 mNormalDeviceIdsWithoutSystemCamera.size());
281}
282
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800283void CameraService::updateCameraNumAndIds() {
284 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700285 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
286 // Excludes hidden secure cameras
287 mNumberOfCameras =
288 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
289 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800290 mNormalDeviceIds =
291 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700292 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800293}
294
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100295void CameraService::addStates(const String8 id) {
296 std::string cameraId(id.c_str());
297 hardware::camera::common::V1_0::CameraResourceCost cost;
298 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
299 if (res != OK) {
300 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
301 return;
302 }
303 std::set<String8> conflicting;
304 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
305 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
306 }
307
308 {
309 Mutex::Autolock lock(mCameraStatesLock);
310 mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
311 conflicting));
312 }
313
314 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100315 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100316 mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800317
318 broadcastTorchModeStatus(id, TorchModeStatus::AVAILABLE_OFF);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100319 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800320
321 updateCameraNumAndIds();
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100322 logDeviceAdded(id, "Device added");
323}
324
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100325void CameraService::removeStates(const String8 id) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800326 updateCameraNumAndIds();
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100327 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100328 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100329 mTorchStatusMap.removeItem(id);
330 }
331
332 {
333 Mutex::Autolock lock(mCameraStatesLock);
334 mCameraStates.erase(id);
335 }
336}
337
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800338void CameraService::onDeviceStatusChanged(const String8& id,
339 CameraDeviceStatus newHalStatus) {
340 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
341 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700342
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800343 StatusInternal newStatus = mapToInternal(newHalStatus);
344
Ruben Brunkcc776712015-02-17 20:18:47 -0800345 std::shared_ptr<CameraState> state = getCameraState(id);
346
347 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700348 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100349 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700350 __FUNCTION__, id.string());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100351
352 // First add as absent to make sure clients are notified below
353 addStates(id);
354
355 updateStatus(newStatus, id);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700356 } else {
357 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
358 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700359 return;
360 }
361
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800362 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800363
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800364 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800365 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700366 return;
367 }
368
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800369 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700370 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
371 newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800372
373 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
374 // to this device until the status changes
375 updateStatus(StatusInternal::NOT_PRESENT, id);
376
Ruben Brunkcc776712015-02-17 20:18:47 -0800377 sp<BasicClient> clientToDisconnect;
Igor Murashkincba2c162013-03-20 15:56:31 -0700378 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800379 // Don't do this in updateStatus to avoid deadlock over mServiceLock
380 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700381
Ruben Brunkcc776712015-02-17 20:18:47 -0800382 // Remove cached shim parameters
383 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700384
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700385 // Remove the client from the list of active clients, if there is one
Ruben Brunkcc776712015-02-17 20:18:47 -0800386 clientToDisconnect = removeClientLocked(id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700387 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800388
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700389 // Disconnect client
390 if (clientToDisconnect.get() != nullptr) {
391 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
392 __FUNCTION__, id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800393 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800394 clientToDisconnect->notifyError(
395 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -0800396 CaptureResultExtras{});
Ruben Brunkcc776712015-02-17 20:18:47 -0800397 // Ensure not in binder RPC so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -0700398 LOG_ALWAYS_FATAL_IF(CameraThreadState::getCallingPid() != getpid(),
Ruben Brunkcc776712015-02-17 20:18:47 -0800399 "onDeviceStatusChanged must be called from the camera service process!");
400 clientToDisconnect->disconnect();
Igor Murashkincba2c162013-03-20 15:56:31 -0700401 }
402
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100403 removeStates(id);
Ruben Brunkcc776712015-02-17 20:18:47 -0800404 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800405 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700406 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
407 newStatus));
408 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800409 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700410 }
411
Igor Murashkincba2c162013-03-20 15:56:31 -0700412}
413
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800414void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800415 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800416 Mutex::Autolock al(mTorchStatusMutex);
417 onTorchStatusChangedLocked(cameraId, newStatus);
418}
419
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800420void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800421 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800422 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
423 __FUNCTION__, cameraId.string(), newStatus);
424
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800425 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800426 status_t res = getTorchStatusLocked(cameraId, &status);
427 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700428 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
429 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800430 return;
431 }
432 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800433 return;
434 }
435
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800436 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800437 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800438 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
439 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800440 return;
441 }
442
Ruben Brunkcc776712015-02-17 20:18:47 -0800443 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700444 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700445 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700446 auto iter = mTorchUidMap.find(cameraId);
447 if (iter != mTorchUidMap.end()) {
448 int oldUid = iter->second.second;
449 int newUid = iter->second.first;
450 BatteryNotifier& notifier(BatteryNotifier::getInstance());
451 if (oldUid != newUid) {
452 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800453 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700454 notifier.noteFlashlightOff(cameraId, oldUid);
455 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800456 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700457 notifier.noteFlashlightOn(cameraId, newUid);
458 }
459 iter->second.second = newUid;
460 } else {
461 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800462 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700463 notifier.noteFlashlightOn(cameraId, oldUid);
464 } else {
465 notifier.noteFlashlightOff(cameraId, oldUid);
466 }
467 }
468 }
469 }
470
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800471 broadcastTorchModeStatus(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800472}
473
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700474static bool hasPermissionsForSystemCamera(int callingPid, int callingUid) {
475 return checkPermission(sSystemCameraPermission, callingPid, callingUid) &&
476 checkPermission(sCameraPermission, callingPid, callingUid);
477}
478
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800479Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700480 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100481 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700482 bool hasSystemCameraPermissions =
483 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
484 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700485 switch (type) {
486 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700487 if (hasSystemCameraPermissions) {
488 *numCameras = static_cast<int>(mNormalDeviceIds.size());
489 } else {
490 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
491 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800492 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700493 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700494 if (hasSystemCameraPermissions) {
495 *numCameras = mNumberOfCameras;
496 } else {
497 *numCameras = mNumberOfCamerasWithoutSystemCamera;
498 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800499 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700500 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800501 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700502 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800503 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
504 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700505 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800506 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700507}
508
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800509Status CameraService::getCameraInfo(int cameraId,
510 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700511 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100512 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700513 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
514 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
515 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
516 "characteristics for system only device %s: ", cameraIdStr.c_str());
517 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100518
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800519 if (!mInitialized) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800520 return STATUS_ERROR(ERROR_DISCONNECTED,
521 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700522 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700523 bool hasSystemCameraPermissions =
524 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
525 CameraThreadState::getCallingUid());
526 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
527 if (hasSystemCameraPermissions) {
528 cameraIdBound = mNumberOfCameras;
529 }
530 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800531 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
532 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700533 }
534
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800535 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800536 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700537 cameraIdStr.c_str(), cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100538 if (err != OK) {
539 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
540 "Error retrieving camera info from device %d: %s (%d)", cameraId,
541 strerror(-err), err);
Ruben Brunkcc776712015-02-17 20:18:47 -0800542 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100543
Ruben Brunkcc776712015-02-17 20:18:47 -0800544 return ret;
545}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700546
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800547std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700548 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
549 auto callingPid = CameraThreadState::getCallingPid();
550 auto callingUid = CameraThreadState::getCallingUid();
551 if (checkPermission(sSystemCameraPermission, callingPid, callingUid) ||
552 getpid() == callingPid) {
553 deviceIds = &mNormalDeviceIds;
554 }
555 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800556 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700557 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800558 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800559 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800560
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700561 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800562}
563
564String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
565 Mutex::Autolock lock(mServiceLock);
566 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800567}
568
569Status CameraService::getCameraCharacteristics(const String16& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800570 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700571 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700572 if (!cameraInfo) {
573 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800574 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700575 }
576
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800577 if (!mInitialized) {
578 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800579 return STATUS_ERROR(ERROR_DISCONNECTED,
580 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700581 }
582
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700583 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
584 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
585 "characteristics for system only device %s: ", String8(cameraId).string());
586 }
587
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800588 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800589
Emilian Peevf53f66e2017-04-11 14:29:43 +0100590 status_t res = mCameraProviderManager->getCameraCharacteristics(
591 String8(cameraId).string(), cameraInfo);
592 if (res != OK) {
593 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
594 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
595 strerror(-res), res);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700596 }
Zhijun He2b59be82013-09-25 10:14:30 -0700597
Jayant Chowdhary12361932018-08-27 14:46:13 -0700598 int callingPid = CameraThreadState::getCallingPid();
599 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100600 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700601 // If it's not calling from cameraserver, check the permission only if
602 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
603 // it would've already been checked in shouldRejectSystemCameraConnection.
Emilian Peeve20c6372018-08-14 18:45:53 +0100604 if ((callingPid != getpid()) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700605 (getSystemCameraKind(String8(cameraId)) != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
606 !checkPermission(sCameraPermission, callingPid, callingUid)) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100607 res = cameraInfo->removePermissionEntries(
608 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
609 &tagsRemoved);
610 if (res != OK) {
611 cameraInfo->clear();
612 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
613 " characteristics needing camera permission for device %s: %s (%d)",
614 String8(cameraId).string(), strerror(-res), res);
615 }
616 }
617
618 if (!tagsRemoved.empty()) {
619 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
620 tagsRemoved.data(), tagsRemoved.size());
621 if (res != OK) {
622 cameraInfo->clear();
623 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
624 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
625 strerror(-res), res);
626 }
627 }
628
Zhijun He2b59be82013-09-25 10:14:30 -0700629 return ret;
630}
631
Ruben Brunkcc776712015-02-17 20:18:47 -0800632String8 CameraService::getFormattedCurrentTime() {
633 time_t now = time(nullptr);
634 char formattedTime[64];
635 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
636 return String8(formattedTime);
637}
638
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800639Status CameraService::getCameraVendorTagDescriptor(
640 /*out*/
641 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700642 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800643 if (!mInitialized) {
644 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800645 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800646 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800647 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
648 if (globalDescriptor != nullptr) {
649 *desc = *(globalDescriptor.get());
650 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800651 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800652}
653
Emilian Peev71c73a22017-03-21 16:35:51 +0000654Status CameraService::getCameraVendorTagCache(
655 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
656 ATRACE_CALL();
657 if (!mInitialized) {
658 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
659 return STATUS_ERROR(ERROR_DISCONNECTED,
660 "Camera subsystem not available");
661 }
662 sp<VendorTagDescriptorCache> globalCache =
663 VendorTagDescriptorCache::getGlobalVendorTagCache();
664 if (globalCache != nullptr) {
665 *cache = *(globalCache.get());
666 }
667 return Status::ok();
668}
669
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800670int CameraService::getDeviceVersion(const String8& cameraId, int* facing) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700671 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800672
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800673 int deviceVersion = 0;
674
Emilian Peevf53f66e2017-04-11 14:29:43 +0100675 status_t res;
676 hardware::hidl_version maxVersion{0,0};
677 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
678 &maxVersion);
679 if (res != OK) return -1;
680 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800681
Emilian Peevf53f66e2017-04-11 14:29:43 +0100682 hardware::CameraInfo info;
683 if (facing) {
684 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800685 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100686 *facing = info.facing;
Igor Murashkin634a5152013-02-20 17:15:11 -0800687 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100688
Igor Murashkin634a5152013-02-20 17:15:11 -0800689 return deviceVersion;
690}
691
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800692Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700693 switch(err) {
694 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800695 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800696 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800697 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
698 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800699 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800700 return STATUS_ERROR(ERROR_DISCONNECTED,
701 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700702 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800703 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
704 "Camera HAL encountered error %d: %s",
705 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700706 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800707}
708
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800709Status CameraService::makeClient(const sp<CameraService>& cameraService,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800710 const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800711 int api1CameraId, int facing, int clientPid, uid_t clientUid, int servicePid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700712 int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
Ruben Brunkcc776712015-02-17 20:18:47 -0800713 /*out*/sp<BasicClient>* client) {
714
Ruben Brunkcc776712015-02-17 20:18:47 -0800715 if (halVersion < 0 || halVersion == deviceVersion) {
716 // Default path: HAL version is unspecified by caller, create CameraClient
717 // based on device version reported by the HAL.
718 switch(deviceVersion) {
719 case CAMERA_DEVICE_API_VERSION_1_0:
720 if (effectiveApiLevel == API_1) { // Camera1 API route
721 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800722 *client = new CameraClient(cameraService, tmp, packageName,
723 api1CameraId, facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700724 getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800725 } else { // Camera2 API route
726 ALOGW("Camera using old HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800727 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800728 "Camera device \"%s\" HAL version %d does not support camera2 API",
729 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800730 }
731 break;
Ruben Brunkcc776712015-02-17 20:18:47 -0800732 case CAMERA_DEVICE_API_VERSION_3_0:
733 case CAMERA_DEVICE_API_VERSION_3_1:
734 case CAMERA_DEVICE_API_VERSION_3_2:
735 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -0700736 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -0700737 case CAMERA_DEVICE_API_VERSION_3_5:
Ruben Brunkcc776712015-02-17 20:18:47 -0800738 if (effectiveApiLevel == API_1) { // Camera1 API route
739 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800740 *client = new Camera2Client(cameraService, tmp, packageName,
741 cameraId, api1CameraId,
742 facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700743 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800744 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800745 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
746 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
747 *client = new CameraDeviceClient(cameraService, tmp, packageName, cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -0800748 facing, clientPid, clientUid, servicePid);
749 }
750 break;
751 default:
752 // Should not be reachable
753 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800754 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800755 "Camera device \"%s\" has unknown HAL version %d",
756 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800757 }
758 } else {
759 // A particular HAL version is requested by caller. Create CameraClient
760 // based on the requested HAL version.
761 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
762 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
763 // Only support higher HAL version device opened as HAL1.0 device.
764 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800765 *client = new CameraClient(cameraService, tmp, packageName,
766 api1CameraId, facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700767 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800768 } else {
769 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
770 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
771 " opened as HAL %x device", halVersion, deviceVersion,
772 CAMERA_DEVICE_API_VERSION_1_0);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800773 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800774 "Camera device \"%s\" (HAL version %d) cannot be opened as HAL version %d",
775 cameraId.string(), deviceVersion, halVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800776 }
777 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800778 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800779}
780
Ruben Brunk6267b532015-04-30 17:44:07 -0700781String8 CameraService::toString(std::set<userid_t> intSet) {
782 String8 s("");
783 bool first = true;
784 for (userid_t i : intSet) {
785 if (first) {
786 s.appendFormat("%d", i);
787 first = false;
788 } else {
789 s.appendFormat(", %d", i);
790 }
791 }
792 return s;
793}
794
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800795int32_t CameraService::mapToInterface(TorchModeStatus status) {
796 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
797 switch (status) {
798 case TorchModeStatus::NOT_AVAILABLE:
799 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
800 break;
801 case TorchModeStatus::AVAILABLE_OFF:
802 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
803 break;
804 case TorchModeStatus::AVAILABLE_ON:
805 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
806 break;
807 default:
808 ALOGW("Unknown new flash status: %d", status);
809 }
810 return serviceStatus;
811}
812
813CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
814 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
815 switch (status) {
816 case CameraDeviceStatus::NOT_PRESENT:
817 serviceStatus = StatusInternal::NOT_PRESENT;
818 break;
819 case CameraDeviceStatus::PRESENT:
820 serviceStatus = StatusInternal::PRESENT;
821 break;
822 case CameraDeviceStatus::ENUMERATING:
823 serviceStatus = StatusInternal::ENUMERATING;
824 break;
825 default:
826 ALOGW("Unknown new HAL device status: %d", status);
827 }
828 return serviceStatus;
829}
830
831int32_t CameraService::mapToInterface(StatusInternal status) {
832 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
833 switch (status) {
834 case StatusInternal::NOT_PRESENT:
835 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
836 break;
837 case StatusInternal::PRESENT:
838 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
839 break;
840 case StatusInternal::ENUMERATING:
841 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
842 break;
843 case StatusInternal::NOT_AVAILABLE:
844 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
845 break;
846 case StatusInternal::UNKNOWN:
847 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
848 break;
849 default:
850 ALOGW("Unknown new internal device status: %d", status);
851 }
852 return serviceStatus;
853}
854
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800855Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -0700856 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700857
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800858 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -0800859 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800860 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800861 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800862 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800863 sp<ICameraClient>{nullptr}, id, cameraId,
864 static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800865 internalPackageName, uid, USE_CALLING_PID,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700866 API_1, /*shimUpdateOnly*/ true, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800867 ).isOk()) {
868 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -0700869 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800870 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700871}
872
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800873Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -0700874 /*out*/
875 CameraParameters* parameters) {
876
877 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
878
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800879 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -0700880
881 if (parameters == NULL) {
882 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800883 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700884 }
885
Ruben Brunkcc776712015-02-17 20:18:47 -0800886 String8 id = String8::format("%d", cameraId);
887
888 // Check if we already have parameters
889 {
890 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700891 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800892 auto cameraState = getCameraState(id);
893 if (cameraState == nullptr) {
894 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800895 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
896 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800897 }
898 CameraParameters p = cameraState->getShimParams();
899 if (!p.isEmpty()) {
900 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800901 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700902 }
903 }
904
Jayant Chowdhary12361932018-08-27 14:46:13 -0700905 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -0800906 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -0700907 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800908 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800909 // Error already logged by callee
910 return ret;
911 }
912
913 // Check for parameters again
914 {
915 // Scope for service lock
916 Mutex::Autolock lock(mServiceLock);
917 auto cameraState = getCameraState(id);
918 if (cameraState == nullptr) {
919 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800920 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
921 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -0700922 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800923 CameraParameters p = cameraState->getShimParams();
924 if (!p.isEmpty()) {
925 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800926 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700927 }
928 }
929
Ruben Brunkcc776712015-02-17 20:18:47 -0800930 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
931 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800932 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700933}
934
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800935// Can camera service trust the caller based on the calling UID?
936static bool isTrustedCallingUid(uid_t uid) {
937 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -0700938 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800939 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -0700940 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800941 return true;
942 default:
943 return false;
944 }
945}
946
Nicholas Sauera3620332019-04-03 14:05:17 -0700947static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
948 PermissionController pc;
949 uid = pc.getPackageUid(packageName, 0);
950 if (uid <= 0) {
951 ALOGE("Unknown package: '%s'", String8(packageName).string());
952 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
953 return BAD_VALUE;
954 }
955
956 if (userId < 0) {
957 ALOGE("Invalid user: %d", userId);
958 dprintf(err, "Invalid user: %d\n", userId);
959 return BAD_VALUE;
960 }
961
962 uid = multiuser_get_uid(userId, uid);
963 return NO_ERROR;
964}
965
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800966Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -0700967 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
968 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -0500969
Alex Deymo9c2a2c22016-08-25 11:59:14 -0700970#ifdef __BRILLO__
971 UNUSED(clientName8);
972 UNUSED(clientUid);
973 UNUSED(clientPid);
974 UNUSED(originalClientPid);
975#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -0700976 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
977 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800978 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -0800979 return allowed;
980 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -0700981#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -0800982
Jayant Chowdhary12361932018-08-27 14:46:13 -0700983 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800984
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800985 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800986 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
987 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800988 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
989 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -0700990 }
991
Ruben Brunkcc776712015-02-17 20:18:47 -0800992 if (getCameraState(cameraId) == nullptr) {
993 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
994 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800995 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
996 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700997 }
998
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800999 status_t err = checkIfDeviceIsUsable(cameraId);
1000 if (err != NO_ERROR) {
1001 switch(err) {
1002 case -ENODEV:
1003 case -EBUSY:
1004 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1005 "No camera device with ID \"%s\" currently available", cameraId.string());
1006 default:
1007 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1008 "Unknown error connecting to ID \"%s\"", cameraId.string());
1009 }
1010 }
1011 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001012}
1013
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001014Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001015 const String8& clientName8, int& clientUid, int& clientPid,
1016 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001017 int callingPid = CameraThreadState::getCallingPid();
1018 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001019
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001020 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001021 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001022 clientUid = callingUid;
1023 } else if (!isTrustedCallingUid(callingUid)) {
1024 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1025 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001026 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1027 "Untrusted caller (calling PID %d, UID %d) trying to "
1028 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1029 callingPid, callingUid, cameraId.string(),
1030 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001031 }
1032
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001033 // Check if we can trust clientPid
1034 if (clientPid == USE_CALLING_PID) {
1035 clientPid = callingPid;
1036 } else if (!isTrustedCallingUid(callingUid)) {
1037 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1038 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001039 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1040 "Untrusted caller (calling PID %d, UID %d) trying to "
1041 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1042 callingPid, callingUid, cameraId.string(),
1043 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001044 }
1045
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001046 if (shouldRejectSystemCameraConnection(cameraId)) {
1047 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1048 cameraId.c_str());
1049 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1050 "available", cameraId.string());
1051 }
1052 // If it's not calling from cameraserver, check the permission if the
1053 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1054 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001055 if (callingPid != getpid() &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001056 (getSystemCameraKind(cameraId) != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
1057 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001058 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001059 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1060 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1061 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001062 }
1063
Svet Ganova453d0d2018-01-11 15:37:58 -08001064 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001065 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001066 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001067 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1068 clientPid, clientUid);
1069 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001070 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1071 "calling UID %d proc state %" PRId32 ")",
1072 clientName8.string(), clientUid, clientPid, cameraId.string(),
1073 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001074 }
1075
Michael Grooverd1d435a2018-12-18 17:39:42 -08001076 // If sensor privacy is enabled then prevent access to the camera
1077 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1078 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1079 return STATUS_ERROR_FMT(ERROR_DISABLED,
1080 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1081 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1082 }
1083
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001084 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1085 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001086 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001087 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001088
Ruben Brunk6267b532015-04-30 17:44:07 -07001089 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001090
Ruben Brunka8ca9152015-04-07 14:23:40 -07001091 // Only allow clients who are being used by the current foreground device user, unless calling
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001092 // from our own process OR the caller is using the cameraserver's HIDL interface.
1093 if (!hardware::IPCThreadState::self()->isServingCall() && callingPid != getpid() &&
1094 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001095 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1096 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1097 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001098 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1099 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1100 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001101 }
1102
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001103 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001104}
1105
1106status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1107 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001108 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001109 if (cameraState == nullptr) {
1110 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1111 cameraId.string());
1112 return -ENODEV;
1113 }
1114
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001115 StatusInternal currentStatus = cameraState->getStatus();
1116 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001117 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1118 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001119 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001120 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001121 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1122 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001123 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001124 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001125
Ruben Brunkcc776712015-02-17 20:18:47 -08001126 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001127}
1128
Ruben Brunkcc776712015-02-17 20:18:47 -08001129void CameraService::finishConnectLocked(const sp<BasicClient>& client,
1130 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001131
Ruben Brunkcc776712015-02-17 20:18:47 -08001132 // Make a descriptor for the incoming client
1133 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
1134 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1135
1136 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1137 String8(client->getPackageName()));
1138
1139 if (evicted.size() > 0) {
1140 // This should never happen - clients should already have been removed in disconnect
1141 for (auto& i : evicted) {
1142 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1143 __FUNCTION__, i->getKey().string());
1144 }
1145
1146 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1147 __FUNCTION__);
1148 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001149
1150 // And register a death notification for the client callback. Do
1151 // this last to avoid Binder policy where a nested Binder
1152 // transaction might be pre-empted to service the client death
1153 // notification if the client process dies before linkToDeath is
1154 // invoked.
1155 sp<IBinder> remoteCallback = client->getRemote();
1156 if (remoteCallback != nullptr) {
1157 remoteCallback->linkToDeath(this);
1158 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001159}
1160
1161status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1162 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
1163 /*out*/
1164 sp<BasicClient>* client,
1165 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001166 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001167 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001168 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001169 DescriptorPtr clientDescriptor;
1170 {
1171 if (effectiveApiLevel == API_1) {
1172 // If we are using API1, any existing client for this camera ID with the same remote
1173 // should be returned rather than evicted to allow MediaRecorder to work properly.
1174
1175 auto current = mActiveClientManager.get(cameraId);
1176 if (current != nullptr) {
1177 auto clientSp = current->getValue();
1178 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001179 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1180 ALOGW("CameraService connect called from same client, but with a different"
1181 " API level, evicting prior client...");
1182 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001183 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001184 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001185 *client = clientSp;
1186 return NO_ERROR;
1187 }
1188 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001189 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001190 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001191
Ruben Brunkcc776712015-02-17 20:18:47 -08001192 // Get current active client PIDs
1193 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1194 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001195
Emilian Peev8131a262017-02-01 12:33:43 +00001196 std::vector<int> priorityScores(ownerPids.size());
1197 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001198
Emilian Peev8131a262017-02-01 12:33:43 +00001199 // Get priority scores of all active PIDs
1200 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1201 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1202 /*out*/&priorityScores[0]);
1203 if (err != OK) {
1204 ALOGE("%s: Priority score query failed: %d",
1205 __FUNCTION__, err);
1206 return err;
1207 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001208
Ruben Brunkcc776712015-02-17 20:18:47 -08001209 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001210 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001211 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001212 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001213 resource_policy::ClientPriority(priorityScores[i], states[i],
1214 /* isVendorClient won't get copied over*/ false));
Ruben Brunkcc776712015-02-17 20:18:47 -08001215 }
1216 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001217
Ruben Brunkcc776712015-02-17 20:18:47 -08001218 // Get state for the given cameraId
1219 auto state = getCameraState(cameraId);
1220 if (state == nullptr) {
1221 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1222 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001223 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001224 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001225 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001226
1227 // Make descriptor for incoming client
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001228 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001229 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1230 state->getConflicting(),
Emilian Peev8131a262017-02-01 12:33:43 +00001231 priorityScores[priorityScores.size() - 1],
1232 clientPid,
1233 states[states.size() - 1]);
Ruben Brunkcc776712015-02-17 20:18:47 -08001234
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001235 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1236
Ruben Brunkcc776712015-02-17 20:18:47 -08001237 // Find clients that would be evicted
1238 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1239
1240 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1241 // background, so we cannot do evictions
1242 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1243 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1244 " priority).", clientPid);
1245
1246 sp<BasicClient> clientSp = clientDescriptor->getValue();
1247 String8 curTime = getFormattedCurrentTime();
1248 auto incompatibleClients =
1249 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1250
1251 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001252 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001253 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001254 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001255
1256 for (auto& i : incompatibleClients) {
1257 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001258 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1259 i->getKey().string(),
1260 String8{i->getValue()->getPackageName()}.string(),
1261 i->getOwnerId(), i->getPriority().getScore(),
1262 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001263 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001264 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001265 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001266 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001267 }
1268
1269 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001270 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001271 mEventLog.add(msg);
1272
1273 return -EBUSY;
1274 }
1275
1276 for (auto& i : evicted) {
1277 sp<BasicClient> clientSp = i->getValue();
1278 if (clientSp.get() == nullptr) {
1279 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1280
1281 // TODO: Remove this
1282 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1283 __FUNCTION__);
1284 mActiveClientManager.remove(i);
1285 continue;
1286 }
1287
1288 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1289 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001290 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001291
Ruben Brunkcc776712015-02-17 20:18:47 -08001292 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001293 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001294 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1295 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001296 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001297 i->getOwnerId(), i->getPriority().getScore(),
1298 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001299 packageName.string(), clientPid, clientPriority.getScore(),
1300 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001301
1302 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001303 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001304 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001305 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001306 }
1307
Ruben Brunkcc776712015-02-17 20:18:47 -08001308 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1309 // other clients from connecting in mServiceLockWrapper if held
1310 mServiceLock.unlock();
1311
1312 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001313 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001314
1315 // Destroy evicted clients
1316 for (auto& i : evictedClients) {
1317 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001318 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001319 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001320
Jayant Chowdhary12361932018-08-27 14:46:13 -07001321 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001322
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001323 for (const auto& i : evictedClients) {
1324 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1325 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1326 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1327 if (ret == TIMED_OUT) {
1328 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1329 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1330 mActiveClientManager.toString().string());
1331 return -EBUSY;
1332 }
1333 if (ret != NO_ERROR) {
1334 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1335 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1336 ret, mActiveClientManager.toString().string());
1337 return ret;
1338 }
1339 }
1340
1341 evictedClients.clear();
1342
Ruben Brunkcc776712015-02-17 20:18:47 -08001343 // Once clients have been disconnected, relock
1344 mServiceLock.lock();
1345
1346 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1347 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1348 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001349 }
1350
Ruben Brunkcc776712015-02-17 20:18:47 -08001351 *partial = clientDescriptor;
1352 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001353}
1354
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001355Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001356 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001357 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001358 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001359 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001360 int clientPid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001361 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001362 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001363
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001364 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001365 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001366
1367 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001368 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001369 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001370 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, clientUid, clientPid, API_1,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001371 /*shimUpdateOnly*/ false, /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001372
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001373 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001374 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001375 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001376 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001377 }
1378
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001379 *device = client;
1380 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001381}
1382
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001383Status CameraService::connectLegacy(
Zhijun Heb10cdad2014-06-16 16:38:35 -07001384 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001385 int api1CameraId, int halVersion,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001386 const String16& clientPackageName,
Zhijun Heb10cdad2014-06-16 16:38:35 -07001387 int clientUid,
1388 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001389 sp<ICamera>* device) {
Zhijun Heb10cdad2014-06-16 16:38:35 -07001390
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001391 ATRACE_CALL();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001392 String8 id = cameraIdIntToStr(api1CameraId);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001393
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001394 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001395 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001396 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId, halVersion,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001397 clientPackageName, clientUid, USE_CALLING_PID, API_1, /*shimUpdateOnly*/ false,
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001398 /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001399
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001400 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001401 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001402 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001403 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001404 }
1405
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001406 *device = client;
1407 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001408}
1409
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001410bool CameraService::shouldSkipStatusUpdates(const String8& cameraId, bool isVendorListener,
1411 int clientPid, int clientUid) const {
1412 SystemCameraKind systemCameraKind = getSystemCameraKind(cameraId);
1413 // If the client is not a vendor client, don't add listener if
1414 // a) the camera is a publicly hidden secure camera OR
1415 // b) the camera is a system only camera and the client doesn't
1416 // have android.permission.SYSTEM_CAMERA permissions.
1417 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1418 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1419 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001420 return true;
1421 }
1422 return false;
1423}
1424
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001425bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1426 // Rules for rejection:
1427 // 1) If cameraserver tries to access this camera device, accept the
1428 // connection.
1429 // 2) The camera device is a publicly hidden secure camera device AND some
1430 // component is trying to access it on a non-hwbinder thread (generally a non HAL client),
1431 // reject it.
1432 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1433 // and the serving thread is a non hwbinder thread, the client must have
1434 // android.permission.SYSTEM_CAMERA permissions to connect.
1435
1436 int cPid = CameraThreadState::getCallingPid();
1437 int cUid = CameraThreadState::getCallingUid();
1438 SystemCameraKind systemCameraKind = getSystemCameraKind(cameraId);
1439
1440 // (1) Cameraserver trying to connect, accept.
1441 if (CameraThreadState::getCallingPid() == getpid()) {
1442 return false;
1443 }
1444 // (2)
1445 if (!hardware::IPCThreadState::self()->isServingCall() &&
1446 systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
1447 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1448 return true;
1449 }
1450 // (3) Here we only check for permissions if it is a system only camera device. This is since
1451 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1452 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1453 // same behavior for system camera devices.
1454 if (!hardware::IPCThreadState::self()->isServingCall() &&
1455 systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1456 !hasPermissionsForSystemCamera(cPid, cUid)) {
1457 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1458 cameraId.c_str());
1459 return true;
1460 }
1461
1462 return false;
1463}
1464
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001465Status CameraService::connectDevice(
1466 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001467 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001468 const String16& clientPackageName,
Ruben Brunkcc776712015-02-17 20:18:47 -08001469 int clientUid,
1470 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001471 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001472
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001473 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001474 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001475 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001476 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001477 String16 clientPackageNameAdj = clientPackageName;
1478 if (hardware::IPCThreadState::self()->isServingCall()) {
1479 std::string vendorClient =
1480 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1481 clientPackageNameAdj = String16(vendorClient.c_str());
1482 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001483 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001484 /*api1CameraId*/-1,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001485 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageNameAdj,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001486 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001487
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001488 if(!ret.isOk()) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001489 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageNameAdj),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001490 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001491 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001492 }
1493
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001494 *device = client;
1495 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001496}
1497
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001498template<class CALLBACK, class CLIENT>
1499Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001500 int api1CameraId, int halVersion, const String16& clientPackageName, int clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001501 int clientPid, apiLevel effectiveApiLevel, bool shimUpdateOnly,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001502 /*out*/sp<CLIENT>& device) {
1503 binder::Status ret = binder::Status::ok();
1504
1505 String8 clientName8(clientPackageName);
1506
1507 int originalClientPid = 0;
1508
1509 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) for HAL version %s and "
1510 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
1511 (halVersion == -1) ? "default" : std::to_string(halVersion).c_str(),
1512 static_cast<int>(effectiveApiLevel));
1513
1514 sp<CLIENT> client = nullptr;
1515 {
1516 // Acquire mServiceLock and prevent other clients from connecting
1517 std::unique_ptr<AutoConditionLock> lock =
1518 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1519
1520 if (lock == nullptr) {
1521 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1522 , clientPid);
1523 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1524 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1525 cameraId.string(), clientName8.string(), clientPid);
1526 }
1527
1528 // Enforce client permissions and do basic sanity checks
1529 if(!(ret = validateConnectLocked(cameraId, clientName8,
1530 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1531 return ret;
1532 }
1533
1534 // Check the shim parameters after acquiring lock, if they have already been updated and
1535 // we were doing a shim update, return immediately
1536 if (shimUpdateOnly) {
1537 auto cameraState = getCameraState(cameraId);
1538 if (cameraState != nullptr) {
1539 if (!cameraState->getShimParams().isEmpty()) return ret;
1540 }
1541 }
1542
1543 status_t err;
1544
1545 sp<BasicClient> clientTmp = nullptr;
1546 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1547 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
1548 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
1549 /*out*/&partial)) != NO_ERROR) {
1550 switch (err) {
1551 case -ENODEV:
1552 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1553 "No camera device with ID \"%s\" currently available",
1554 cameraId.string());
1555 case -EBUSY:
1556 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1557 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1558 cameraId.string());
1559 default:
1560 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1561 "Unexpected error %s (%d) opening camera \"%s\"",
1562 strerror(-err), err, cameraId.string());
1563 }
1564 }
1565
1566 if (clientTmp.get() != nullptr) {
1567 // Handle special case for API1 MediaRecorder where the existing client is returned
1568 device = static_cast<CLIENT*>(clientTmp.get());
1569 return ret;
1570 }
1571
1572 // give flashlight a chance to close devices if necessary.
1573 mFlashlight->prepareDeviceOpen(cameraId);
1574
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001575 int facing = -1;
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001576 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001577 if (facing == -1) {
1578 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1579 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1580 "Unable to get camera device \"%s\" facing", cameraId.string());
1581 }
1582
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001583 sp<BasicClient> tmp = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001584 if(!(ret = makeClient(this, cameraCb, clientPackageName,
1585 cameraId, api1CameraId, facing,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001586 clientPid, clientUid, getpid(),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001587 halVersion, deviceVersion, effectiveApiLevel,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001588 /*out*/&tmp)).isOk()) {
1589 return ret;
1590 }
1591 client = static_cast<CLIENT*>(tmp.get());
1592
1593 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1594 __FUNCTION__);
1595
Emilian Peevbd8c5032018-02-14 23:05:40 +00001596 err = client->initialize(mCameraProviderManager, mMonitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001597 if (err != OK) {
1598 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001599 // Errors could be from the HAL module open call or from AppOpsManager
1600 switch(err) {
1601 case BAD_VALUE:
1602 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1603 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1604 case -EBUSY:
1605 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1606 "Camera \"%s\" is already open", cameraId.string());
1607 case -EUSERS:
1608 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1609 "Too many cameras already open, cannot open camera \"%s\"",
1610 cameraId.string());
1611 case PERMISSION_DENIED:
1612 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1613 "No permission to open camera \"%s\"", cameraId.string());
1614 case -EACCES:
1615 return STATUS_ERROR_FMT(ERROR_DISABLED,
1616 "Camera \"%s\" disabled by policy", cameraId.string());
1617 case -ENODEV:
1618 default:
1619 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1620 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1621 strerror(-err), err);
1622 }
1623 }
1624
1625 // Update shim paremeters for legacy clients
1626 if (effectiveApiLevel == API_1) {
1627 // Assume we have always received a Client subclass for API1
1628 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1629 String8 rawParams = shimClient->getParameters();
1630 CameraParameters params(rawParams);
1631
1632 auto cameraState = getCameraState(cameraId);
1633 if (cameraState != nullptr) {
1634 cameraState->setShimParams(params);
1635 } else {
1636 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1637 __FUNCTION__, cameraId.string());
1638 }
1639 }
1640
1641 if (shimUpdateOnly) {
1642 // If only updating legacy shim parameters, immediately disconnect client
1643 mServiceLock.unlock();
1644 client->disconnect();
1645 mServiceLock.lock();
1646 } else {
1647 // Otherwise, add client to active clients list
1648 finishConnectLocked(client, partial);
1649 }
1650 } // lock is destroyed, allow further connect calls
1651
1652 // Important: release the mutex here so the client can call back into the service from its
1653 // destructor (can be at the end of the call)
1654 device = client;
1655 return ret;
1656}
1657
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001658Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001659 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001660 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001661
1662 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001663 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001664 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001665 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1666 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001667 }
1668
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001669 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07001670 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001671
1672 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001673 auto state = getCameraState(id);
1674 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001675 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001676 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1677 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001678 }
1679
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001680 StatusInternal cameraStatus = state->getStatus();
1681 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001682 cameraStatus != StatusInternal::NOT_AVAILABLE) {
1683 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001684 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1685 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001686 }
1687
1688 {
1689 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001690 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001691 status_t err = getTorchStatusLocked(id, &status);
1692 if (err != OK) {
1693 if (err == NAME_NOT_FOUND) {
1694 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1695 "Camera \"%s\" does not have a flash unit", id.string());
1696 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001697 ALOGE("%s: getting current torch status failed for camera %s",
1698 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001699 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1700 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
1701 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001702 }
1703
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001704 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001705 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001706 ALOGE("%s: torch mode of camera %s is not available because "
1707 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001708 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1709 "Torch for camera \"%s\" is not available due to an existing camera user",
1710 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001711 } else {
1712 ALOGE("%s: torch mode of camera %s is not available due to "
1713 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001714 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1715 "Torch for camera \"%s\" is not available due to insufficient resources",
1716 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001717 }
1718 }
1719 }
1720
Ruben Brunk99e69712015-05-26 17:25:07 -07001721 {
1722 // Update UID map - this is used in the torch status changed callbacks, so must be done
1723 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001724 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001725 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1726 mTorchUidMap[id].first = uid;
1727 mTorchUidMap[id].second = uid;
1728 } else {
1729 // Set the pending UID
1730 mTorchUidMap[id].first = uid;
1731 }
1732 }
1733
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001734 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001735
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001736 if (err != OK) {
1737 int32_t errorCode;
1738 String8 msg;
1739 switch (err) {
1740 case -ENOSYS:
1741 msg = String8::format("Camera \"%s\" has no flashlight",
1742 id.string());
1743 errorCode = ERROR_ILLEGAL_ARGUMENT;
1744 break;
1745 default:
1746 msg = String8::format(
1747 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1748 id.string(), enabled, strerror(-err), err);
1749 errorCode = ERROR_INVALID_OPERATION;
1750 }
1751 ALOGE("%s: %s", __FUNCTION__, msg.string());
1752 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001753 }
1754
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001755 {
1756 // update the link to client's death
1757 Mutex::Autolock al(mTorchClientMapMutex);
1758 ssize_t index = mTorchClientMap.indexOfKey(id);
1759 if (enabled) {
1760 if (index == NAME_NOT_FOUND) {
1761 mTorchClientMap.add(id, clientBinder);
1762 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001763 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001764 mTorchClientMap.replaceValueAt(index, clientBinder);
1765 }
1766 clientBinder->linkToDeath(this);
1767 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001768 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001769 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001770 }
1771
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07001772 int clientPid = CameraThreadState::getCallingPid();
1773 const char *id_cstr = id.c_str();
1774 const char *torchState = enabled ? "on" : "off";
1775 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
1776 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001777 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001778}
1779
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001780Status CameraService::notifySystemEvent(int32_t eventId,
1781 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001782 const int pid = CameraThreadState::getCallingPid();
1783 const int selfPid = getpid();
1784
1785 // Permission checks
1786 if (pid != selfPid) {
1787 // Ensure we're being called by system_server, or similar process with
1788 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001789 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001790 const int uid = CameraThreadState::getCallingUid();
1791 ALOGE("Permission Denial: cannot send updates to camera service about system"
1792 " events from pid=%d, uid=%d", pid, uid);
1793 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09001794 "No permission to send updates to camera service about system events"
1795 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001796 }
1797 }
1798
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001799 ATRACE_CALL();
1800
Ruben Brunk36597b22015-03-20 22:15:57 -07001801 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001802 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001803 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07001804 // from a system server crash
1805 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08001806 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001807 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07001808 break;
1809 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001810 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07001811 default: {
1812 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1813 eventId);
1814 break;
1815 }
1816 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001817 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07001818}
1819
Emilian Peev53722fa2019-02-22 17:47:20 -08001820void CameraService::notifyMonitoredUids() {
1821 Mutex::Autolock lock(mStatusListenerLock);
1822
1823 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001824 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08001825 if (!ret.isOk()) {
1826 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
1827 ret.exceptionCode());
1828 }
1829 }
1830}
1831
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08001832Status CameraService::notifyDeviceStateChange(int64_t newState) {
1833 const int pid = CameraThreadState::getCallingPid();
1834 const int selfPid = getpid();
1835
1836 // Permission checks
1837 if (pid != selfPid) {
1838 // Ensure we're being called by system_server, or similar process with
1839 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001840 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08001841 const int uid = CameraThreadState::getCallingUid();
1842 ALOGE("Permission Denial: cannot send updates to camera service about device"
1843 " state changes from pid=%d, uid=%d", pid, uid);
1844 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1845 "No permission to send updates to camera service about device state"
1846 " changes from pid=%d, uid=%d", pid, uid);
1847 }
1848 }
1849
1850 ATRACE_CALL();
1851
1852 using hardware::camera::provider::V2_5::DeviceState;
1853 hardware::hidl_bitfield<DeviceState> newDeviceState{};
1854 if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
1855 newDeviceState |= DeviceState::BACK_COVERED;
1856 }
1857 if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
1858 newDeviceState |= DeviceState::FRONT_COVERED;
1859 }
1860 if (newState & ICameraService::DEVICE_STATE_FOLDED) {
1861 newDeviceState |= DeviceState::FOLDED;
1862 }
1863 // Only map vendor bits directly
1864 uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
1865 newDeviceState |= vendorBits;
1866
1867 ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
1868 Mutex::Autolock l(mServiceLock);
1869 mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
1870
1871 return Status::ok();
1872}
1873
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001874Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
1875 /*out*/
1876 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001877 return addListenerHelper(listener, cameraStatuses);
1878}
1879
1880Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
1881 /*out*/
1882 std::vector<hardware::CameraStatus> *cameraStatuses,
1883 bool isVendorListener) {
1884
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001885 ATRACE_CALL();
1886
Igor Murashkinbfc99152013-02-27 12:55:20 -08001887 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08001888
Ruben Brunk3450ba72015-06-16 11:00:37 -07001889 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001890 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001891 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001892 }
1893
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001894 auto clientUid = CameraThreadState::getCallingUid();
1895 auto clientPid = CameraThreadState::getCallingPid();
1896
Igor Murashkinbfc99152013-02-27 12:55:20 -08001897 Mutex::Autolock lock(mServiceLock);
1898
Ruben Brunkcc776712015-02-17 20:18:47 -08001899 {
1900 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08001901 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001902 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001903 ALOGW("%s: Tried to add listener %p which was already subscribed",
1904 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001905 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08001906 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001907 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001908
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001909 sp<ServiceListener> serviceListener =
1910 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08001911 auto ret = serviceListener->initialize();
1912 if (ret != NO_ERROR) {
1913 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
1914 strerror(-ret), ret);
1915 ALOGE("%s: %s", __FUNCTION__, msg.string());
1916 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
1917 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001918 // The listener still needs to be added to the list of listeners, regardless of what
1919 // permissions the listener process has / whether it is a vendor listener. Since it might be
1920 // eligible to listen to other camera ids.
1921 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08001922 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08001923 }
1924
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001925 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07001926 {
Ruben Brunkcc776712015-02-17 20:18:47 -08001927 Mutex::Autolock lock(mCameraStatesLock);
1928 for (auto& i : mCameraStates) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001929 if (shouldSkipStatusUpdates(i.first, isVendorListener, clientPid, clientUid)) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001930 ALOGV("Cannot add public listener for hidden system-only %s for pid %d",
1931 i.first.c_str(), CameraThreadState::getCallingPid());
1932 continue;
1933 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001934 cameraStatuses->emplace_back(i.first, mapToInterface(i.second->getStatus()));
Igor Murashkincba2c162013-03-20 15:56:31 -07001935 }
1936 }
1937
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001938 /*
1939 * Immediately signal current torch status to this listener only
1940 * This may be a subset of all the devices, so don't include it in the response directly
1941 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001942 {
1943 Mutex::Autolock al(mTorchStatusMutex);
1944 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001945 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001946 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001947 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001948 }
1949
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001950 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08001951}
Ruben Brunkcc776712015-02-17 20:18:47 -08001952
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001953Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001954 ATRACE_CALL();
1955
Igor Murashkinbfc99152013-02-27 12:55:20 -08001956 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
1957
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001958 if (listener == 0) {
1959 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001960 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001961 }
1962
Igor Murashkinbfc99152013-02-27 12:55:20 -08001963 Mutex::Autolock lock(mServiceLock);
1964
Ruben Brunkcc776712015-02-17 20:18:47 -08001965 {
1966 Mutex::Autolock lock(mStatusListenerLock);
1967 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001968 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
1969 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
1970 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08001971 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001972 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001973 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001974 }
1975 }
1976
1977 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
1978 __FUNCTION__, listener.get());
1979
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001980 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08001981}
1982
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001983Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001984
1985 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001986 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1987
1988 if (parameters == NULL) {
1989 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001990 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001991 }
1992
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001993 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001994
1995 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001996 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07001997 // Error logged by caller
1998 return ret;
1999 }
2000
2001 String8 shimParamsString8 = shimParams.flatten();
2002 String16 shimParamsString16 = String16(shimParamsString8);
2003
2004 *parameters = shimParamsString16;
2005
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002006 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002007}
2008
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002009Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2010 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002011 ATRACE_CALL();
2012
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002013 const String8 id = String8(cameraId);
2014
2015 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002016
2017 switch (apiVersion) {
2018 case API_VERSION_1:
2019 case API_VERSION_2:
2020 break;
2021 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002022 String8 msg = String8::format("Unknown API version %d", apiVersion);
2023 ALOGE("%s: %s", __FUNCTION__, msg.string());
2024 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002025 }
2026
Emilian Peev28ad2ea2017-02-07 16:14:32 +00002027 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002028 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002029 case CAMERA_DEVICE_API_VERSION_1_0:
2030 case CAMERA_DEVICE_API_VERSION_3_0:
2031 case CAMERA_DEVICE_API_VERSION_3_1:
2032 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002033 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2034 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002035 *isSupported = false;
2036 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002037 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2038 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002039 *isSupported = true;
2040 }
2041 break;
2042 case CAMERA_DEVICE_API_VERSION_3_2:
2043 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07002044 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002045 case CAMERA_DEVICE_API_VERSION_3_5:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002046 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2047 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002048 *isSupported = true;
2049 break;
2050 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002051 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002052 ALOGE("%s: %s", __FUNCTION__, msg.string());
2053 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002054 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002055 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002056 String8 msg = String8::format("Unknown device version %x for device %s",
2057 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002058 ALOGE("%s: %s", __FUNCTION__, msg.string());
2059 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2060 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002061 }
2062
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002063 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002064}
2065
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002066Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2067 /*out*/ bool *isSupported) {
2068 ATRACE_CALL();
2069
2070 const String8 id = String8(cameraId);
2071
2072 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2073 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2074
2075 return Status::ok();
2076}
2077
Ruben Brunkcc776712015-02-17 20:18:47 -08002078void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002079 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002080 for (auto& i : mActiveClientManager.getAll()) {
2081 auto clientSp = i->getValue();
2082 if (clientSp.get() == client) {
2083 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002084 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002085 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002086 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002087}
2088
Ruben Brunkcc776712015-02-17 20:18:47 -08002089bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002090 bool ret = false;
2091 {
2092 // Acquire mServiceLock and prevent other clients from connecting
2093 std::unique_ptr<AutoConditionLock> lock =
2094 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002095
Igor Murashkin634a5152013-02-20 17:15:11 -08002096
Ruben Brunkcc776712015-02-17 20:18:47 -08002097 std::vector<sp<BasicClient>> evicted;
2098 for (auto& i : mActiveClientManager.getAll()) {
2099 auto clientSp = i->getValue();
2100 if (clientSp.get() == nullptr) {
2101 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2102 mActiveClientManager.remove(i);
2103 continue;
2104 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002105 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002106 mActiveClientManager.remove(i);
2107 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002108
Ruben Brunkcc776712015-02-17 20:18:47 -08002109 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002110 clientSp->notifyError(
2111 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002112 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002113 }
2114 }
2115
Ruben Brunkcc776712015-02-17 20:18:47 -08002116 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2117 // other clients from connecting in mServiceLockWrapper if held
2118 mServiceLock.unlock();
2119
Ruben Brunk36597b22015-03-20 22:15:57 -07002120 // Do not clear caller identity, remote caller should be client proccess
2121
Ruben Brunkcc776712015-02-17 20:18:47 -08002122 for (auto& i : evicted) {
2123 if (i.get() != nullptr) {
2124 i->disconnect();
2125 ret = true;
2126 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002127 }
2128
Ruben Brunkcc776712015-02-17 20:18:47 -08002129 // Reacquire mServiceLock
2130 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002131
Ruben Brunkcc776712015-02-17 20:18:47 -08002132 } // lock is destroyed, allow further connect calls
2133
2134 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002135}
2136
Ruben Brunkcc776712015-02-17 20:18:47 -08002137std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2138 const String8& cameraId) const {
2139 std::shared_ptr<CameraState> state;
2140 {
2141 Mutex::Autolock lock(mCameraStatesLock);
2142 auto iter = mCameraStates.find(cameraId);
2143 if (iter != mCameraStates.end()) {
2144 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002145 }
2146 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002147 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002148}
2149
Ruben Brunkcc776712015-02-17 20:18:47 -08002150sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2151 // Remove from active clients list
2152 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2153 if (clientDescriptorPtr == nullptr) {
2154 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2155 cameraId.string());
2156 return sp<BasicClient>{nullptr};
2157 }
2158
2159 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07002160}
2161
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002162void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002163 // Acquire mServiceLock and prevent other clients from connecting
2164 std::unique_ptr<AutoConditionLock> lock =
2165 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2166
Ruben Brunk6267b532015-04-30 17:44:07 -07002167 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002168 for (size_t i = 0; i < newUserIds.size(); i++) {
2169 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002170 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002171 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002172 return;
2173 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002174 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002175 }
2176
Ruben Brunka8ca9152015-04-07 14:23:40 -07002177
Ruben Brunk6267b532015-04-30 17:44:07 -07002178 if (newAllowedUsers == mAllowedUsers) {
2179 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2180 return;
2181 }
2182
2183 logUserSwitch(mAllowedUsers, newAllowedUsers);
2184
2185 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002186
2187 // Current user has switched, evict all current clients.
2188 std::vector<sp<BasicClient>> evicted;
2189 for (auto& i : mActiveClientManager.getAll()) {
2190 auto clientSp = i->getValue();
2191
2192 if (clientSp.get() == nullptr) {
2193 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2194 continue;
2195 }
2196
Ruben Brunk6267b532015-04-30 17:44:07 -07002197 // Don't evict clients that are still allowed.
2198 uid_t clientUid = clientSp->getClientUid();
2199 userid_t clientUserId = multiuser_get_user_id(clientUid);
2200 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2201 continue;
2202 }
2203
Ruben Brunk36597b22015-03-20 22:15:57 -07002204 evicted.push_back(clientSp);
2205
2206 String8 curTime = getFormattedCurrentTime();
2207
2208 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2209 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002210
Ruben Brunk36597b22015-03-20 22:15:57 -07002211 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002212 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002213 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2214 " to user switch.", i->getKey().string(),
2215 String8{clientSp->getPackageName()}.string(),
2216 i->getOwnerId(), i->getPriority().getScore(),
2217 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002218
2219 }
2220
2221 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2222 // blocking other clients from connecting in mServiceLockWrapper if held.
2223 mServiceLock.unlock();
2224
2225 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002226 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002227
2228 for (auto& i : evicted) {
2229 i->disconnect();
2230 }
2231
Jayant Chowdhary12361932018-08-27 14:46:13 -07002232 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002233
2234 // Reacquire mServiceLock
2235 mServiceLock.lock();
2236}
Ruben Brunkcc776712015-02-17 20:18:47 -08002237
Ruben Brunka8ca9152015-04-07 14:23:40 -07002238void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002239 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002240 Mutex::Autolock l(mLogLock);
2241 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002242}
2243
Ruben Brunka8ca9152015-04-07 14:23:40 -07002244void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002245 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002246 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002247 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002248 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002249}
2250
2251void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002252 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002253 // Log the clients evicted
2254 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002255 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002256}
2257
2258void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002259 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002260 // Log the client rejected
2261 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002262 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002263}
2264
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002265void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
2266 // Log torch event
2267 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
2268 torchState, clientPid));
2269}
2270
Ruben Brunk6267b532015-04-30 17:44:07 -07002271void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
2272 const std::set<userid_t>& newUserIds) {
2273 String8 newUsers = toString(newUserIds);
2274 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002275 if (oldUsers.size() == 0) {
2276 oldUsers = "<None>";
2277 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07002278 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002279 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07002280 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002281}
2282
2283void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
2284 // Log the device removal
2285 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
2286}
2287
2288void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
2289 // Log the device removal
2290 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
2291}
2292
2293void CameraService::logClientDied(int clientPid, const char* reason) {
2294 // Log the device removal
2295 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07002296}
2297
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002298void CameraService::logServiceError(const char* msg, int errorCode) {
2299 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002300 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002301}
2302
Ruben Brunk36597b22015-03-20 22:15:57 -07002303status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
2304 uint32_t flags) {
2305
Mathias Agopian65ab4712010-07-14 17:59:35 -07002306 // Permission checks
2307 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002308 case SHELL_COMMAND_TRANSACTION: {
2309 int in = data.readFileDescriptor();
2310 int out = data.readFileDescriptor();
2311 int err = data.readFileDescriptor();
2312 int argc = data.readInt32();
2313 Vector<String16> args;
2314 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
2315 args.add(data.readString16());
2316 }
2317 sp<IBinder> unusedCallback;
2318 sp<IResultReceiver> resultReceiver;
2319 status_t status;
2320 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
2321 return status;
2322 }
2323 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
2324 return status;
2325 }
2326 status = shellCommand(in, out, err, args);
2327 if (resultReceiver != nullptr) {
2328 resultReceiver->send(status);
2329 }
2330 return NO_ERROR;
2331 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002332 }
2333
2334 return BnCameraService::onTransact(code, data, reply, flags);
2335}
2336
Mathias Agopian65ab4712010-07-14 17:59:35 -07002337// We share the media players for shutter and recording sound for all clients.
2338// A reference count is kept to determine when we will actually release the
2339// media players.
2340
Jaekyun Seokef498052018-03-23 13:09:44 +09002341sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
2342 sp<MediaPlayer> mp = new MediaPlayer();
2343 status_t error;
2344 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08002345 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09002346 error = mp->prepare();
2347 }
2348 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002349 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09002350 mp->disconnect();
2351 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002352 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002353 }
2354 return mp;
2355}
2356
username5755fea2018-12-27 09:48:08 +08002357void CameraService::increaseSoundRef() {
2358 Mutex::Autolock lock(mSoundLock);
2359 mSoundRef++;
2360}
2361
2362void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002363 ATRACE_CALL();
2364
username5755fea2018-12-27 09:48:08 +08002365 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
2366 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
2367 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
2368 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
2369 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2370 }
2371 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
2372 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
2373 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
2374 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002375 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08002376 }
2377 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
2378 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
2379 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
2380 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2381 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002382 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002383}
2384
username5755fea2018-12-27 09:48:08 +08002385void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002386 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002387 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002388 if (--mSoundRef) return;
2389
2390 for (int i = 0; i < NUM_SOUNDS; i++) {
2391 if (mSoundPlayer[i] != 0) {
2392 mSoundPlayer[i]->disconnect();
2393 mSoundPlayer[i].clear();
2394 }
2395 }
2396}
2397
2398void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002399 ATRACE_CALL();
2400
Mathias Agopian65ab4712010-07-14 17:59:35 -07002401 LOG1("playSound(%d)", kind);
2402 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002403 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002404 sp<MediaPlayer> player = mSoundPlayer[kind];
2405 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08002406 player->seekTo(0);
2407 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002408 }
2409}
2410
2411// ----------------------------------------------------------------------------
2412
2413CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002414 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002415 const String16& clientPackageName,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002416 const String8& cameraIdStr,
2417 int api1CameraId, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002418 int clientPid, uid_t clientUid,
2419 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002420 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08002421 IInterface::asBinder(cameraClient),
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002422 clientPackageName,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002423 cameraIdStr, cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002424 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002425 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002426 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08002427{
Jayant Chowdhary12361932018-08-27 14:46:13 -07002428 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002429 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002430
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002431 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002432
username5755fea2018-12-27 09:48:08 +08002433 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002434
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002435 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002436}
2437
Mathias Agopian65ab4712010-07-14 17:59:35 -07002438// tear down the client
2439CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002440 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08002441 mDestructionStarted = true;
2442
username5755fea2018-12-27 09:48:08 +08002443 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002444 // unconditionally disconnect. function is idempotent
2445 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002446}
2447
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002448sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
2449
Igor Murashkin634a5152013-02-20 17:15:11 -08002450CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002451 const sp<IBinder>& remoteCallback,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002452 const String16& clientPackageName,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002453 const String8& cameraIdStr, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002454 int clientPid, uid_t clientUid,
2455 int servicePid):
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002456 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing),
2457 mClientPackageName(clientPackageName), mClientPid(clientPid), mClientUid(clientUid),
2458 mServicePid(servicePid),
2459 mDisconnected(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002460 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002461 mRemoteBinder(remoteCallback)
Igor Murashkin634a5152013-02-20 17:15:11 -08002462{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002463 if (sCameraService == nullptr) {
2464 sCameraService = cameraService;
2465 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002466 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08002467 mDestructionStarted = false;
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08002468
2469 // In some cases the calling code has no access to the package it runs under.
2470 // For example, NDK camera API.
2471 // In this case we will get the packages for the calling UID and pick the first one
2472 // for attributing the app op. This will work correctly for runtime permissions
2473 // as for legacy apps we will toggle the app op for all packages in the UID.
2474 // The caveat is that the operation may be attributed to the wrong package and
2475 // stats based on app ops may be slightly off.
2476 if (mClientPackageName.size() <= 0) {
2477 sp<IServiceManager> sm = defaultServiceManager();
2478 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2479 if (binder == 0) {
2480 ALOGE("Cannot get permission service");
2481 // Leave mClientPackageName unchanged (empty) and the further interaction
2482 // with camera will fail in BasicClient::startCameraOps
2483 return;
2484 }
2485
2486 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2487 Vector<String16> packages;
2488
2489 permCtrl->getPackagesForUid(mClientUid, packages);
2490
2491 if (packages.isEmpty()) {
2492 ALOGE("No packages for calling UID");
2493 // Leave mClientPackageName unchanged (empty) and the further interaction
2494 // with camera will fail in BasicClient::startCameraOps
2495 return;
2496 }
2497 mClientPackageName = packages[0];
2498 }
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002499 if (!hardware::IPCThreadState::self()->isServingCall()) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002500 mAppOpsManager = std::make_unique<AppOpsManager>();
2501 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002502}
2503
2504CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002505 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08002506 mDestructionStarted = true;
2507}
2508
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002509binder::Status CameraService::BasicClient::disconnect() {
2510 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002511 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002512 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07002513 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002514 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002515
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002516 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002517 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07002518 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
2519 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002520
2521 sp<IBinder> remote = getRemote();
2522 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002523 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08002524 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002525
2526 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07002527 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002528 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
2529 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
2530 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002531
Igor Murashkincba2c162013-03-20 15:56:31 -07002532 // client shouldn't be able to call into us anymore
2533 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002534
2535 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08002536}
2537
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002538status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2539 // No dumping of clients directly over Binder,
2540 // must go through CameraService::dump
2541 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002542 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002543 return OK;
2544}
2545
Ruben Brunkcc776712015-02-17 20:18:47 -08002546String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002547 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08002548}
2549
2550
2551int CameraService::BasicClient::getClientPid() const {
2552 return mClientPid;
2553}
2554
Ruben Brunk6267b532015-04-30 17:44:07 -07002555uid_t CameraService::BasicClient::getClientUid() const {
2556 return mClientUid;
2557}
2558
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002559bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2560 // Defaults to API2.
2561 return level == API_2;
2562}
2563
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002564status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002565 {
2566 Mutex::Autolock l(mAudioRestrictionLock);
2567 mAudioRestriction = mode;
2568 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002569 sCameraService->updateAudioRestriction();
2570 return OK;
2571}
2572
2573int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002574 return sCameraService->updateAudioRestriction();
2575}
2576
2577int32_t CameraService::BasicClient::getAudioRestriction() const {
2578 Mutex::Autolock l(mAudioRestrictionLock);
2579 return mAudioRestriction;
2580}
2581
2582bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
2583 switch (mode) {
2584 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
2585 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
2586 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
2587 return true;
2588 default:
2589 return false;
2590 }
2591}
2592
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002593status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002594 ATRACE_CALL();
2595
Igor Murashkine6800ce2013-03-04 17:25:57 -08002596 {
2597 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002598 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002599 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002600 if (mAppOpsManager != nullptr) {
2601 // Notify app ops that the camera is not available
2602 mOpsCallback = new OpsCallback(this);
2603 int32_t res;
2604 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
2605 mClientPackageName, mOpsCallback);
2606 res = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA,
2607 mClientUid, mClientPackageName, /*startIfModeDefault*/ false);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002608
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002609 if (res == AppOpsManager::MODE_ERRORED) {
2610 ALOGI("Camera %s: Access for \"%s\" has been revoked",
2611 mCameraIdStr.string(), String8(mClientPackageName).string());
2612 return PERMISSION_DENIED;
2613 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002614
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002615 if (res == AppOpsManager::MODE_IGNORED) {
2616 ALOGI("Camera %s: Access for \"%s\" has been restricted",
2617 mCameraIdStr.string(), String8(mClientPackageName).string());
2618 // Return the same error as for device policy manager rejection
2619 return -EACCES;
2620 }
Svetoslav28e8ef72015-05-11 19:21:31 -07002621 }
2622
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002623 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002624
2625 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002626 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002627
Emilian Peev573291c2018-02-10 02:10:56 +00002628 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2629 if (canCastToApiClient(API_2)) {
2630 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2631 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002632 // Transition device state to OPEN
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002633 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
Emilian Peev573291c2018-02-10 02:10:56 +00002634 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002635
Emilian Peev53722fa2019-02-22 17:47:20 -08002636 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
2637
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002638 return OK;
2639}
2640
2641status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002642 ATRACE_CALL();
2643
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002644 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002645 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002646 // Notify app ops that the camera is available again
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002647 if (mAppOpsManager != nullptr) {
2648 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
2649 mClientPackageName);
2650 mOpsActive = false;
2651 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002652 // This function is called when a client disconnects. This should
2653 // release the camera, but actually only if it was in a proper
2654 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002655 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002656 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002657
Ruben Brunkcc776712015-02-17 20:18:47 -08002658 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002659 sCameraService->updateStatus(StatusInternal::PRESENT,
2660 mCameraIdStr, rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002661
Emilian Peev573291c2018-02-10 02:10:56 +00002662 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2663 if (canCastToApiClient(API_2)) {
2664 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2665 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002666 // Transition device state to CLOSED
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002667 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
Emilian Peev573291c2018-02-10 02:10:56 +00002668 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002669 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002670 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002671 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
2672 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002673 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002674 mOpsCallback.clear();
2675
Emilian Peev53722fa2019-02-22 17:47:20 -08002676 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
2677
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002678 return OK;
2679}
2680
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002681void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002682 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002683 if (mAppOpsManager == nullptr) {
2684 return;
2685 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002686 if (op != AppOpsManager::OP_CAMERA) {
2687 ALOGW("Unexpected app ops notification received: %d", op);
2688 return;
2689 }
2690
2691 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002692 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002693 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002694 ALOGV("checkOp returns: %d, %s ", res,
2695 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
2696 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
2697 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
2698 "UNKNOWN");
2699
2700 if (res != AppOpsManager::MODE_ALLOWED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002701 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002702 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08002703 block();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002704 }
2705}
2706
Svet Ganova453d0d2018-01-11 15:37:58 -08002707void CameraService::BasicClient::block() {
2708 ATRACE_CALL();
2709
2710 // Reset the client PID to allow server-initiated disconnect,
2711 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07002712 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08002713 CaptureResultExtras resultExtras; // a dummy result (invalid)
2714 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
2715 disconnect();
2716}
2717
Mathias Agopian65ab4712010-07-14 17:59:35 -07002718// ----------------------------------------------------------------------------
2719
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002720void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07002721 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002722 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07002723 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07002724 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
2725 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
2726 api1ErrorCode = CAMERA_ERROR_DISABLED;
2727 }
2728 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07002729 } else {
2730 ALOGE("mRemoteCallback is NULL!!");
2731 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002732}
2733
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002734// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002735binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002736 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002737 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08002738}
2739
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002740bool CameraService::Client::canCastToApiClient(apiLevel level) const {
2741 return level == API_1;
2742}
2743
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002744CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
2745 mClient(client) {
2746}
2747
2748void CameraService::Client::OpsCallback::opChanged(int32_t op,
2749 const String16& packageName) {
2750 sp<BasicClient> client = mClient.promote();
2751 if (client != NULL) {
2752 client->opChanged(op, packageName);
2753 }
2754}
2755
Mathias Agopian65ab4712010-07-14 17:59:35 -07002756// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08002757// UidPolicy
2758// ----------------------------------------------------------------------------
2759
2760void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002761 Mutex::Autolock _l(mUidLock);
2762
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002763 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07002764 status_t res = mAm.linkToDeath(this);
2765 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08002766 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08002767 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08002768 ActivityManager::PROCESS_STATE_UNKNOWN,
2769 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002770 if (res == OK) {
2771 mRegistered = true;
2772 ALOGV("UidPolicy: Registered with ActivityManager");
2773 }
Svet Ganova453d0d2018-01-11 15:37:58 -08002774}
2775
2776void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002777 Mutex::Autolock _l(mUidLock);
2778
Steven Moreland2f348142019-07-02 15:59:07 -07002779 mAm.unregisterUidObserver(this);
2780 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002781 mRegistered = false;
2782 mActiveUids.clear();
2783 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08002784}
2785
2786void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
2787 onUidIdle(uid, disabled);
2788}
2789
2790void CameraService::UidPolicy::onUidActive(uid_t uid) {
2791 Mutex::Autolock _l(mUidLock);
2792 mActiveUids.insert(uid);
2793}
2794
2795void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
2796 bool deleted = false;
2797 {
2798 Mutex::Autolock _l(mUidLock);
2799 if (mActiveUids.erase(uid) > 0) {
2800 deleted = true;
2801 }
2802 }
2803 if (deleted) {
2804 sp<CameraService> service = mService.promote();
2805 if (service != nullptr) {
2806 service->blockClientsForUid(uid);
2807 }
2808 }
2809}
2810
Emilian Peev53722fa2019-02-22 17:47:20 -08002811void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
2812 int64_t /*procStateSeq*/) {
2813 bool procStateChange = false;
2814 {
2815 Mutex::Autolock _l(mUidLock);
2816 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
2817 (mMonitoredUids[uid].first != procState)) {
2818 mMonitoredUids[uid].first = procState;
2819 procStateChange = true;
2820 }
2821 }
2822
2823 if (procStateChange) {
2824 sp<CameraService> service = mService.promote();
2825 if (service != nullptr) {
2826 service->notifyMonitoredUids();
2827 }
2828 }
2829}
2830
2831void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
2832 Mutex::Autolock _l(mUidLock);
2833 auto it = mMonitoredUids.find(uid);
2834 if (it != mMonitoredUids.end()) {
2835 it->second.second++;
2836 } else {
2837 mMonitoredUids.emplace(
2838 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
2839 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
2840 }
2841}
2842
2843void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
2844 Mutex::Autolock _l(mUidLock);
2845 auto it = mMonitoredUids.find(uid);
2846 if (it != mMonitoredUids.end()) {
2847 it->second.second--;
2848 if (it->second.second == 0) {
2849 mMonitoredUids.erase(it);
2850 }
2851 } else {
2852 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
2853 }
2854}
2855
Svet Ganov7b4ab782018-03-25 12:48:10 -07002856bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002857 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07002858 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08002859}
2860
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07002861static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
2862static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07002863
Svet Ganov7b4ab782018-03-25 12:48:10 -07002864bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002865 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002866 // If activity manager is unreachable, assume everything is active
2867 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002868 return true;
2869 }
2870 auto it = mOverrideUids.find(uid);
2871 if (it != mOverrideUids.end()) {
2872 return it->second;
2873 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07002874 bool active = mActiveUids.find(uid) != mActiveUids.end();
2875 if (!active) {
2876 // We want active UIDs to always access camera with their first attempt since
2877 // there is no guarantee the app is robustly written and would retry getting
2878 // the camera on failure. The inverse case is not a problem as we would take
2879 // camera away soon once we get the callback that the uid is no longer active.
2880 ActivityManager am;
2881 // Okay to access with a lock held as UID changes are dispatched without
2882 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07002883 int64_t startTimeMillis = 0;
2884 do {
2885 // TODO: Fix this b/109950150!
2886 // Okay this is a hack. There is a race between the UID turning active and
2887 // activity being resumed. The proper fix is very risky, so we temporary add
2888 // some polling which should happen pretty rarely anyway as the race is hard
2889 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07002890 active = mActiveUids.find(uid) != mActiveUids.end();
2891 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07002892 if (active) {
2893 break;
2894 }
2895 if (startTimeMillis <= 0) {
2896 startTimeMillis = uptimeMillis();
2897 }
2898 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07002899 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07002900 if (remainingTimeMillis <= 0) {
2901 break;
2902 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07002903 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
2904
2905 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07002906 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07002907 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07002908 } while (true);
2909
Svet Ganov7b4ab782018-03-25 12:48:10 -07002910 if (active) {
2911 // Now that we found out the UID is actually active, cache that
2912 mActiveUids.insert(uid);
2913 }
2914 }
2915 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08002916}
2917
Varun Shahb42f1eb2019-04-16 14:45:13 -07002918int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
2919 Mutex::Autolock _l(mUidLock);
2920 return getProcStateLocked(uid);
2921}
2922
2923int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
2924 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
2925 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
2926 procState = mMonitoredUids[uid].first;
2927 }
2928 return procState;
2929}
2930
Svet Ganov7b4ab782018-03-25 12:48:10 -07002931void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
2932 String16 callingPackage, bool active) {
2933 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08002934}
2935
Svet Ganov7b4ab782018-03-25 12:48:10 -07002936void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
2937 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08002938}
2939
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002940void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
2941 Mutex::Autolock _l(mUidLock);
2942 ALOGV("UidPolicy: ActivityManager has died");
2943 mRegistered = false;
2944 mActiveUids.clear();
2945}
2946
Svet Ganov7b4ab782018-03-25 12:48:10 -07002947void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
2948 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002949 bool wasActive = false;
2950 bool isActive = false;
2951 {
2952 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07002953 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08002954 mOverrideUids.erase(uid);
2955 if (insert) {
2956 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
2957 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07002958 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08002959 }
2960 if (wasActive != isActive && !isActive) {
2961 sp<CameraService> service = mService.promote();
2962 if (service != nullptr) {
2963 service->blockClientsForUid(uid);
2964 }
2965 }
2966}
2967
2968// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08002969// SensorPrivacyPolicy
2970// ----------------------------------------------------------------------------
2971void CameraService::SensorPrivacyPolicy::registerSelf() {
2972 Mutex::Autolock _l(mSensorPrivacyLock);
2973 if (mRegistered) {
2974 return;
2975 }
2976 SensorPrivacyManager spm;
2977 spm.addSensorPrivacyListener(this);
2978 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
2979 status_t res = spm.linkToDeath(this);
2980 if (res == OK) {
2981 mRegistered = true;
2982 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
2983 }
2984}
2985
2986void CameraService::SensorPrivacyPolicy::unregisterSelf() {
2987 Mutex::Autolock _l(mSensorPrivacyLock);
2988 SensorPrivacyManager spm;
2989 spm.removeSensorPrivacyListener(this);
2990 spm.unlinkToDeath(this);
2991 mRegistered = false;
2992 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
2993}
2994
2995bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
2996 Mutex::Autolock _l(mSensorPrivacyLock);
2997 return mSensorPrivacyEnabled;
2998}
2999
3000binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3001 {
3002 Mutex::Autolock _l(mSensorPrivacyLock);
3003 mSensorPrivacyEnabled = enabled;
3004 }
3005 // if sensor privacy is enabled then block all clients from accessing the camera
3006 if (enabled) {
3007 sp<CameraService> service = mService.promote();
3008 if (service != nullptr) {
3009 service->blockAllClients();
3010 }
3011 }
3012 return binder::Status::ok();
3013}
3014
3015void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3016 Mutex::Autolock _l(mSensorPrivacyLock);
3017 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3018 mRegistered = false;
3019}
3020
3021// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003022// CameraState
3023// ----------------------------------------------------------------------------
3024
3025CameraService::CameraState::CameraState(const String8& id, int cost,
3026 const std::set<String8>& conflicting) : mId(id),
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003027 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003028
3029CameraService::CameraState::~CameraState() {}
3030
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003031CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003032 Mutex::Autolock lock(mStatusLock);
3033 return mStatus;
3034}
3035
3036CameraParameters CameraService::CameraState::getShimParams() const {
3037 return mShimParams;
3038}
3039
3040void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3041 mShimParams = params;
3042}
3043
3044int CameraService::CameraState::getCost() const {
3045 return mCost;
3046}
3047
3048std::set<String8> CameraService::CameraState::getConflicting() const {
3049 return mConflicting;
3050}
3051
3052String8 CameraService::CameraState::getId() const {
3053 return mId;
3054}
3055
3056// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07003057// ClientEventListener
3058// ----------------------------------------------------------------------------
3059
3060void CameraService::ClientEventListener::onClientAdded(
3061 const resource_policy::ClientDescriptor<String8,
3062 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003063 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003064 if (basicClient.get() != nullptr) {
3065 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3066 notifier.noteStartCamera(descriptor.getKey(),
3067 static_cast<int>(basicClient->getClientUid()));
3068 }
3069}
3070
3071void CameraService::ClientEventListener::onClientRemoved(
3072 const resource_policy::ClientDescriptor<String8,
3073 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003074 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003075 if (basicClient.get() != nullptr) {
3076 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3077 notifier.noteStopCamera(descriptor.getKey(),
3078 static_cast<int>(basicClient->getClientUid()));
3079 }
3080}
3081
3082
3083// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003084// CameraClientManager
3085// ----------------------------------------------------------------------------
3086
Ruben Brunk99e69712015-05-26 17:25:07 -07003087CameraService::CameraClientManager::CameraClientManager() {
3088 setListener(std::make_shared<ClientEventListener>());
3089}
3090
Ruben Brunkcc776712015-02-17 20:18:47 -08003091CameraService::CameraClientManager::~CameraClientManager() {}
3092
3093sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
3094 const String8& id) const {
3095 auto descriptor = get(id);
3096 if (descriptor == nullptr) {
3097 return sp<BasicClient>{nullptr};
3098 }
3099 return descriptor->getValue();
3100}
3101
3102String8 CameraService::CameraClientManager::toString() const {
3103 auto all = getAll();
3104 String8 ret("[");
3105 bool hasAny = false;
3106 for (auto& i : all) {
3107 hasAny = true;
3108 String8 key = i->getKey();
3109 int32_t cost = i->getCost();
3110 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00003111 int32_t score = i->getPriority().getScore();
3112 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08003113 auto conflicting = i->getConflicting();
3114 auto clientSp = i->getValue();
3115 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07003116 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08003117 if (clientSp.get() != nullptr) {
3118 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07003119 uid_t clientUid = clientSp->getClientUid();
3120 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003121 }
Emilian Peev8131a262017-02-01 12:33:43 +00003122 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
3123 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08003124
Ruben Brunk6267b532015-04-30 17:44:07 -07003125 if (clientSp.get() != nullptr) {
3126 ret.appendFormat("User Id: %d, ", clientUserId);
3127 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003128 if (packageName.size() != 0) {
3129 ret.appendFormat("Client Package Name: %s", packageName.string());
3130 }
3131
3132 ret.append(", Conflicting Client Devices: {");
3133 for (auto& j : conflicting) {
3134 ret.appendFormat("%s, ", j.string());
3135 }
3136 ret.append("})");
3137 }
3138 if (hasAny) ret.append("\n");
3139 ret.append("]\n");
3140 return ret;
3141}
3142
3143CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3144 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00003145 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
3146 int32_t state) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003147
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003148 bool isVendorClient = hardware::IPCThreadState::self()->isServingCall();
3149 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
3150 int32_t state_adj = isVendorClient ? kVendorClientState: state;
3151
Ruben Brunkcc776712015-02-17 20:18:47 -08003152 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003153 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08003154}
3155
3156CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3157 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
3158 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00003159 partial->getConflicting(), partial->getPriority().getScore(),
3160 partial->getOwnerId(), partial->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08003161}
3162
3163// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07003164
3165static const int kDumpLockRetries = 50;
3166static const int kDumpLockSleep = 60000;
3167
3168static bool tryLock(Mutex& mutex)
3169{
3170 bool locked = false;
3171 for (int i = 0; i < kDumpLockRetries; ++i) {
3172 if (mutex.tryLock() == NO_ERROR) {
3173 locked = true;
3174 break;
3175 }
3176 usleep(kDumpLockSleep);
3177 }
3178 return locked;
3179}
3180
3181status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003182 ATRACE_CALL();
3183
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003184 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003185 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003186 CameraThreadState::getCallingPid(),
3187 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003188 return NO_ERROR;
3189 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003190 bool locked = tryLock(mServiceLock);
3191 // failed to lock - CameraService is probably deadlocked
3192 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003193 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003194 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003195
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003196 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003197 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07003198
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003199 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003200 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08003201
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003202 if (locked) mServiceLock.unlock();
3203 return NO_ERROR;
3204 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003205 dprintf(fd, "\n== Service global info: ==\n\n");
3206 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003207 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07003208 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
3209 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003210 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
3211 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
3212 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003213 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003214 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
3215 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003216
3217 dumpEventLog(fd);
3218
3219 bool stateLocked = tryLock(mCameraStatesLock);
3220 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003221 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003222 }
3223
Emilian Peevbd8c5032018-02-14 23:05:40 +00003224 int argSize = args.size();
3225 for (int i = 0; i < argSize; i++) {
3226 if (args[i] == TagMonitor::kMonitorOption) {
3227 if (i + 1 < argSize) {
3228 mMonitorTags = String8(args[i + 1]);
3229 }
3230 break;
3231 }
3232 }
3233
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003234 for (auto& state : mCameraStates) {
3235 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003236
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003237 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003238
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003239 CameraParameters p = state.second->getShimParams();
3240 if (!p.isEmpty()) {
3241 dprintf(fd, " Camera1 API shim is using parameters:\n ");
3242 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003243 }
3244
3245 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08003246 if (clientDescriptor != nullptr) {
3247 dprintf(fd, " Device %s is open. Client instance dump:\n",
3248 cameraId.string());
3249 dprintf(fd, " Client priority score: %d state: %d\n",
3250 clientDescriptor->getPriority().getScore(),
3251 clientDescriptor->getPriority().getState());
3252 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
3253
3254 auto client = clientDescriptor->getValue();
3255 dprintf(fd, " Client package: %s\n",
3256 String8(client->getPackageName()).string());
3257
3258 client->dumpClient(fd, args);
3259 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003260 dprintf(fd, " Device %s is closed, no client instance\n",
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003261 cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003262 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003263
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003264 }
3265
3266 if (stateLocked) mCameraStatesLock.unlock();
3267
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003268 if (locked) mServiceLock.unlock();
3269
Emilian Peevf53f66e2017-04-11 14:29:43 +01003270 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003271
3272 dprintf(fd, "\n== Vendor tags: ==\n\n");
3273
3274 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
3275 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00003276 sp<VendorTagDescriptorCache> cache =
3277 VendorTagDescriptorCache::getGlobalVendorTagCache();
3278 if (cache == NULL) {
3279 dprintf(fd, "No vendor tags.\n");
3280 } else {
3281 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
3282 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003283 } else {
3284 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
3285 }
3286
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003287 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003288 dprintf(fd, "\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003289 camera3::CameraTraces::dump(fd, args);
3290
3291 // Process dump arguments, if any
3292 int n = args.size();
3293 String16 verboseOption("-v");
3294 String16 unreachableOption("--unreachable");
3295 for (int i = 0; i < n; i++) {
3296 if (args[i] == verboseOption) {
3297 // change logging level
3298 if (i + 1 >= n) continue;
3299 String8 levelStr(args[i+1]);
3300 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003301 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003302 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003303 } else if (args[i] == unreachableOption) {
3304 // Dump memory analysis
3305 // TODO - should limit be an argument parameter?
3306 UnreachableMemoryInfo info;
3307 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
3308 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003309 dprintf(fd, "\n== Unable to dump unreachable memory. "
3310 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003311 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003312 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003313 std::string s = info.ToString(/*log_contents*/ true);
3314 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003315 }
3316 }
3317 }
3318 return NO_ERROR;
3319}
3320
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003321void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003322 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003323
3324 Mutex::Autolock l(mLogLock);
3325 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003326 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003327 }
3328
3329 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003330 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003331 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003332 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003333 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003334 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003335}
3336
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003337void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003338 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003339 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
3340 if (mTorchClientMap[i] == who) {
3341 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003342 String8 cameraId = mTorchClientMap.keyAt(i);
3343 status_t res = mFlashlight->setTorchMode(cameraId, false);
3344 if (res) {
3345 ALOGE("%s: torch client died but couldn't turn off torch: "
3346 "%s (%d)", __FUNCTION__, strerror(-res), res);
3347 return;
3348 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003349 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003350 break;
3351 }
3352 }
3353}
3354
Ruben Brunkcc776712015-02-17 20:18:47 -08003355/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003356
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003357 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07003358 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
3359 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003360 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003361 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003362 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003363
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003364 // check torch client
3365 handleTorchClientBinderDied(who);
3366
3367 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08003368 if(!evictClientIdByRemote(who)) {
3369 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003370 return;
3371 }
3372
Ruben Brunkcc776712015-02-17 20:18:47 -08003373 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
3374 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003375}
3376
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003377void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003378 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08003379}
3380
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003381void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
3382 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003383 // Do not lock mServiceLock here or can get into a deadlock from
3384 // connect() -> disconnect -> updateStatus
3385
3386 auto state = getCameraState(cameraId);
3387
3388 if (state == nullptr) {
3389 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
3390 cameraId.string());
3391 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07003392 }
3393
Ruben Brunkcc776712015-02-17 20:18:47 -08003394 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
3395 // of the listeners with both the mStatusStatus and mStatusListenerLock held
3396 state->updateStatus(status, cameraId, rejectSourceStates, [this]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003397 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003398
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003399 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003400 // Update torch status if it has a flash unit.
3401 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003402 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003403 if (getTorchStatusLocked(cameraId, &torchStatus) !=
3404 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003405 TorchModeStatus newTorchStatus =
3406 status == StatusInternal::PRESENT ?
3407 TorchModeStatus::AVAILABLE_OFF :
3408 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003409 if (torchStatus != newTorchStatus) {
3410 onTorchStatusChangedLocked(cameraId, newTorchStatus);
3411 }
3412 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003413 }
3414
3415 Mutex::Autolock lock(mStatusListenerLock);
3416
3417 for (auto& listener : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003418 if (shouldSkipStatusUpdates(cameraId, listener->isVendorListener(),
3419 listener->getListenerPid(), listener->getListenerUid())) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003420 ALOGV("Skipping camera discovery callback for system-only camera %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003421 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003422 continue;
3423 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003424 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08003425 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08003426 }
3427 });
Igor Murashkincba2c162013-03-20 15:56:31 -07003428}
3429
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003430template<class Func>
3431void CameraService::CameraState::updateStatus(StatusInternal status,
3432 const String8& cameraId,
3433 std::initializer_list<StatusInternal> rejectSourceStates,
3434 Func onStatusUpdatedLocked) {
3435 Mutex::Autolock lock(mStatusLock);
3436 StatusInternal oldStatus = mStatus;
3437 mStatus = status;
3438
3439 if (oldStatus == status) {
3440 return;
3441 }
3442
3443 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
3444 cameraId.string(), oldStatus, status);
3445
3446 if (oldStatus == StatusInternal::NOT_PRESENT &&
3447 (status != StatusInternal::PRESENT &&
3448 status != StatusInternal::ENUMERATING)) {
3449
3450 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
3451 __FUNCTION__);
3452 mStatus = oldStatus;
3453 return;
3454 }
3455
3456 /**
3457 * Sometimes we want to conditionally do a transition.
3458 * For example if a client disconnects, we want to go to PRESENT
3459 * only if we weren't already in NOT_PRESENT or ENUMERATING.
3460 */
3461 for (auto& rejectStatus : rejectSourceStates) {
3462 if (oldStatus == rejectStatus) {
3463 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
3464 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
3465 mStatus = oldStatus;
3466 return;
3467 }
3468 }
3469
3470 onStatusUpdatedLocked(cameraId, status);
3471}
3472
Eino-Ville Talvalae8c96c72017-06-27 12:24:07 -07003473void CameraService::updateProxyDeviceState(int newState,
Emilian Peev573291c2018-02-10 02:10:56 +00003474 const String8& cameraId, int facing, const String16& clientName, int apiLevel) {
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003475 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
3476 if (proxyBinder == nullptr) return;
3477 String16 id(cameraId);
Emilian Peev573291c2018-02-10 02:10:56 +00003478 proxyBinder->notifyCameraState(id, newState, facing, clientName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003479}
3480
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003481status_t CameraService::getTorchStatusLocked(
3482 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003483 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003484 if (!status) {
3485 return BAD_VALUE;
3486 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003487 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3488 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003489 // invalid camera ID or the camera doesn't have a flash unit
3490 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003491 }
3492
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003493 *status = mTorchStatusMap.valueAt(index);
3494 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003495}
3496
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003497status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003498 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003499 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3500 if (index == NAME_NOT_FOUND) {
3501 return BAD_VALUE;
3502 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003503 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003504
3505 return OK;
3506}
3507
Svet Ganova453d0d2018-01-11 15:37:58 -08003508void CameraService::blockClientsForUid(uid_t uid) {
3509 const auto clients = mActiveClientManager.getAll();
3510 for (auto& current : clients) {
3511 if (current != nullptr) {
3512 const auto basicClient = current->getValue();
3513 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
3514 basicClient->block();
3515 }
3516 }
3517 }
3518}
3519
Michael Grooverd1d435a2018-12-18 17:39:42 -08003520void CameraService::blockAllClients() {
3521 const auto clients = mActiveClientManager.getAll();
3522 for (auto& current : clients) {
3523 if (current != nullptr) {
3524 const auto basicClient = current->getValue();
3525 if (basicClient.get() != nullptr) {
3526 basicClient->block();
3527 }
3528 }
3529 }
3530}
3531
Svet Ganova453d0d2018-01-11 15:37:58 -08003532// NOTE: This is a remote API - make sure all args are validated
3533status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
3534 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
3535 return PERMISSION_DENIED;
3536 }
3537 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
3538 return BAD_VALUE;
3539 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003540 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003541 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003542 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003543 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003544 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003545 return handleGetUidState(args, out, err);
3546 } else if (args.size() == 1 && args[0] == String16("help")) {
3547 printHelp(out);
3548 return NO_ERROR;
3549 }
3550 printHelp(err);
3551 return BAD_VALUE;
3552}
3553
3554status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003555 String16 packageName = args[1];
3556
Svet Ganova453d0d2018-01-11 15:37:58 -08003557 bool active = false;
3558 if (args[2] == String16("active")) {
3559 active = true;
3560 } else if ((args[2] != String16("idle"))) {
3561 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
3562 return BAD_VALUE;
3563 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003564
3565 int userId = 0;
3566 if (args.size() >= 5 && args[3] == String16("--user")) {
3567 userId = atoi(String8(args[4]));
3568 }
3569
3570 uid_t uid;
3571 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
3572 return BAD_VALUE;
3573 }
3574
3575 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08003576 return NO_ERROR;
3577}
3578
3579status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003580 String16 packageName = args[1];
3581
3582 int userId = 0;
3583 if (args.size() >= 4 && args[2] == String16("--user")) {
3584 userId = atoi(String8(args[3]));
3585 }
3586
3587 uid_t uid;
3588 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003589 return BAD_VALUE;
3590 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003591
3592 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08003593 return NO_ERROR;
3594}
3595
3596status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003597 String16 packageName = args[1];
3598
3599 int userId = 0;
3600 if (args.size() >= 4 && args[2] == String16("--user")) {
3601 userId = atoi(String8(args[3]));
3602 }
3603
3604 uid_t uid;
3605 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003606 return BAD_VALUE;
3607 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003608
3609 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003610 return dprintf(out, "active\n");
3611 } else {
3612 return dprintf(out, "idle\n");
3613 }
3614}
3615
3616status_t CameraService::printHelp(int out) {
3617 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07003618 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
3619 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
3620 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08003621 " help print this message\n");
3622}
3623
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003624int32_t CameraService::updateAudioRestriction() {
3625 Mutex::Autolock lock(mServiceLock);
3626 return updateAudioRestrictionLocked();
3627}
3628
3629int32_t CameraService::updateAudioRestrictionLocked() {
3630 int32_t mode = 0;
3631 // iterate through all active client
3632 for (const auto& i : mActiveClientManager.getAll()) {
3633 const auto clientSp = i->getValue();
3634 mode |= clientSp->getAudioRestriction();
3635 }
3636
3637 bool modeChanged = (mAudioRestriction != mode);
3638 mAudioRestriction = mode;
3639 if (modeChanged) {
3640 mAppOps.setCameraAudioRestriction(mode);
3641 }
3642 return mode;
3643}
3644
Mathias Agopian65ab4712010-07-14 17:59:35 -07003645}; // namespace android