blob: 9a91ea06896273066f09c55b1f0f15103ae6a2c6 [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),
Emilian Peevf53f66e2017-04-11 14:29:43 +0100138 mSoundRef(0), mInitialized(false) {
Steve Blockdf64d152012-01-04 20:05:49 +0000139 ALOGI("CameraService started (pid=%d)", getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800140 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700141}
142
Iliyan Malchev8951a972011-04-14 16:55:59 -0700143void CameraService::onFirstRef()
144{
Ruben Brunkcc776712015-02-17 20:18:47 -0800145 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800146
Iliyan Malchev8951a972011-04-14 16:55:59 -0700147 BnCameraService::onFirstRef();
148
Ruben Brunk99e69712015-05-26 17:25:07 -0700149 // Update battery life tracking if service is restarting
150 BatteryNotifier& notifier(BatteryNotifier::getInstance());
151 notifier.noteResetCamera();
152 notifier.noteResetFlashlight();
153
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800154 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800155
Emilian Peevf53f66e2017-04-11 14:29:43 +0100156 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800157 if (res == OK) {
158 mInitialized = true;
159 }
160
161 CameraService::pingCameraServiceProxy();
Svet Ganova453d0d2018-01-11 15:37:58 -0800162
163 mUidPolicy = new UidPolicy(this);
164 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800165 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
166 mSensorPrivacyPolicy->registerSelf();
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700167 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
168 if (hcs->registerAsService() != android::OK) {
169 ALOGE("%s: Failed to register default android.frameworks.cameraservice.service@1.0",
170 __FUNCTION__);
171 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800172}
173
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800174status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800175 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100176
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800177 std::vector<std::string> deviceIds;
178 {
179 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800180
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800181 if (nullptr == mCameraProviderManager.get()) {
182 mCameraProviderManager = new CameraProviderManager();
183 res = mCameraProviderManager->initialize(this);
184 if (res != OK) {
185 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
186 __FUNCTION__, strerror(-res), res);
187 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100188 }
189 }
190
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800191
192 // Setup vendor tags before we call get_camera_info the first time
193 // because HAL might need to setup static vendor keys in get_camera_info
194 // TODO: maybe put this into CameraProviderManager::initialize()?
195 mCameraProviderManager->setUpVendorTags();
196
197 if (nullptr == mFlashlight.get()) {
198 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700199 }
200
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800201 res = mFlashlight->findFlashUnits();
202 if (res != OK) {
203 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
204 }
205
206 deviceIds = mCameraProviderManager->getCameraDeviceIds();
207 }
208
209
210 for (auto& cameraId : deviceIds) {
211 String8 id8 = String8(cameraId.c_str());
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800212 if (getCameraState(id8) == nullptr) {
213 onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
214 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800215 }
216
217 return OK;
218}
219
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700220sp<ICameraServiceProxy> CameraService::getCameraServiceProxy() {
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800221#ifndef __BRILLO__
Eino-Ville Talvala7d5569f2019-04-08 13:57:54 -0700222 Mutex::Autolock al(sProxyMutex);
223 if (sCameraServiceProxy == nullptr) {
224 sp<IServiceManager> sm = defaultServiceManager();
225 // Use checkService because cameraserver normally starts before the
226 // system server and the proxy service. So the long timeout that getService
227 // has before giving up is inappropriate.
228 sp<IBinder> binder = sm->checkService(String16("media.camera.proxy"));
229 if (binder != nullptr) {
230 sCameraServiceProxy = interface_cast<ICameraServiceProxy>(binder);
231 }
Ruben Brunk2823ce02015-05-19 17:25:13 -0700232 }
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800233#endif
Eino-Ville Talvala7d5569f2019-04-08 13:57:54 -0700234 return sCameraServiceProxy;
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700235}
236
237void CameraService::pingCameraServiceProxy() {
238 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
239 if (proxyBinder == nullptr) return;
Ruben Brunk2823ce02015-05-19 17:25:13 -0700240 proxyBinder->pingForUserUpdate();
Iliyan Malchev8951a972011-04-14 16:55:59 -0700241}
242
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800243void CameraService::broadcastTorchModeStatus(const String8& cameraId, TorchModeStatus status) {
244 Mutex::Autolock lock(mStatusListenerLock);
245
246 for (auto& i : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700247 i->getListener()->onTorchStatusChanged(mapToInterface(status), String16{cameraId});
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800248 }
249}
250
Mathias Agopian65ab4712010-07-14 17:59:35 -0700251CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800252 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800253 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800254 mSensorPrivacyPolicy->unregisterSelf();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700255}
256
Emilian Peevaee727d2017-05-04 16:35:48 +0100257void CameraService::onNewProviderRegistered() {
258 enumerateProviders();
259}
260
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800261void CameraService::updateCameraNumAndIds() {
262 Mutex::Autolock l(mServiceLock);
263 mNumberOfCameras = mCameraProviderManager->getCameraCount();
264 mNormalDeviceIds =
265 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
266}
267
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100268void CameraService::addStates(const String8 id) {
269 std::string cameraId(id.c_str());
270 hardware::camera::common::V1_0::CameraResourceCost cost;
271 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
272 if (res != OK) {
273 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
274 return;
275 }
276 std::set<String8> conflicting;
277 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
278 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
279 }
280
281 {
282 Mutex::Autolock lock(mCameraStatesLock);
283 mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
284 conflicting));
285 }
286
287 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100288 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100289 mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800290
291 broadcastTorchModeStatus(id, TorchModeStatus::AVAILABLE_OFF);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100292 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800293
294 updateCameraNumAndIds();
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100295 logDeviceAdded(id, "Device added");
296}
297
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100298void CameraService::removeStates(const String8 id) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800299 updateCameraNumAndIds();
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100300 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100301 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100302 mTorchStatusMap.removeItem(id);
303 }
304
305 {
306 Mutex::Autolock lock(mCameraStatesLock);
307 mCameraStates.erase(id);
308 }
309}
310
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800311void CameraService::onDeviceStatusChanged(const String8& id,
312 CameraDeviceStatus newHalStatus) {
313 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
314 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700315
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800316 StatusInternal newStatus = mapToInternal(newHalStatus);
317
Ruben Brunkcc776712015-02-17 20:18:47 -0800318 std::shared_ptr<CameraState> state = getCameraState(id);
319
320 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700321 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100322 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700323 __FUNCTION__, id.string());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100324
325 // First add as absent to make sure clients are notified below
326 addStates(id);
327
328 updateStatus(newStatus, id);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700329 } else {
330 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
331 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700332 return;
333 }
334
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800335 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800336
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800337 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800338 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700339 return;
340 }
341
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800342 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700343 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
344 newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800345
346 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
347 // to this device until the status changes
348 updateStatus(StatusInternal::NOT_PRESENT, id);
349
Ruben Brunkcc776712015-02-17 20:18:47 -0800350 sp<BasicClient> clientToDisconnect;
Igor Murashkincba2c162013-03-20 15:56:31 -0700351 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800352 // Don't do this in updateStatus to avoid deadlock over mServiceLock
353 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700354
Ruben Brunkcc776712015-02-17 20:18:47 -0800355 // Remove cached shim parameters
356 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700357
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700358 // Remove the client from the list of active clients, if there is one
Ruben Brunkcc776712015-02-17 20:18:47 -0800359 clientToDisconnect = removeClientLocked(id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700360 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800361
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700362 // Disconnect client
363 if (clientToDisconnect.get() != nullptr) {
364 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
365 __FUNCTION__, id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800366 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800367 clientToDisconnect->notifyError(
368 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -0800369 CaptureResultExtras{});
Ruben Brunkcc776712015-02-17 20:18:47 -0800370 // Ensure not in binder RPC so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -0700371 LOG_ALWAYS_FATAL_IF(CameraThreadState::getCallingPid() != getpid(),
Ruben Brunkcc776712015-02-17 20:18:47 -0800372 "onDeviceStatusChanged must be called from the camera service process!");
373 clientToDisconnect->disconnect();
Igor Murashkincba2c162013-03-20 15:56:31 -0700374 }
375
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100376 removeStates(id);
Ruben Brunkcc776712015-02-17 20:18:47 -0800377 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800378 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700379 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
380 newStatus));
381 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800382 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700383 }
384
Igor Murashkincba2c162013-03-20 15:56:31 -0700385}
386
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800387void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800388 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800389 Mutex::Autolock al(mTorchStatusMutex);
390 onTorchStatusChangedLocked(cameraId, newStatus);
391}
392
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800393void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800394 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800395 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
396 __FUNCTION__, cameraId.string(), newStatus);
397
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800398 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800399 status_t res = getTorchStatusLocked(cameraId, &status);
400 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700401 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
402 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800403 return;
404 }
405 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800406 return;
407 }
408
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800409 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800410 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800411 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
412 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800413 return;
414 }
415
Ruben Brunkcc776712015-02-17 20:18:47 -0800416 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700417 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700418 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700419 auto iter = mTorchUidMap.find(cameraId);
420 if (iter != mTorchUidMap.end()) {
421 int oldUid = iter->second.second;
422 int newUid = iter->second.first;
423 BatteryNotifier& notifier(BatteryNotifier::getInstance());
424 if (oldUid != newUid) {
425 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800426 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700427 notifier.noteFlashlightOff(cameraId, oldUid);
428 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800429 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700430 notifier.noteFlashlightOn(cameraId, newUid);
431 }
432 iter->second.second = newUid;
433 } else {
434 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800435 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700436 notifier.noteFlashlightOn(cameraId, oldUid);
437 } else {
438 notifier.noteFlashlightOff(cameraId, oldUid);
439 }
440 }
441 }
442 }
443
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800444 broadcastTorchModeStatus(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800445}
446
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800447Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700448 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100449 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700450 switch (type) {
451 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800452 *numCameras = static_cast<int>(mNormalDeviceIds.size());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800453 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700454 case CAMERA_TYPE_ALL:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800455 *numCameras = mNumberOfCameras;
456 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700457 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800458 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700459 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800460 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
461 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700462 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800463 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700464}
465
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800466Status CameraService::getCameraInfo(int cameraId,
467 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700468 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100469 Mutex::Autolock l(mServiceLock);
470
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800471 if (!mInitialized) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800472 return STATUS_ERROR(ERROR_DISCONNECTED,
473 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700474 }
475
Mathias Agopian65ab4712010-07-14 17:59:35 -0700476 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800477 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
478 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700479 }
480
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800481 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800482 status_t err = mCameraProviderManager->getCameraInfo(
483 cameraIdIntToStrLocked(cameraId), cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100484 if (err != OK) {
485 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
486 "Error retrieving camera info from device %d: %s (%d)", cameraId,
487 strerror(-err), err);
Ruben Brunkcc776712015-02-17 20:18:47 -0800488 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100489
Ruben Brunkcc776712015-02-17 20:18:47 -0800490 return ret;
491}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700492
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800493std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
494 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(mNormalDeviceIds.size())) {
495 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
496 __FUNCTION__, cameraIdInt, mNormalDeviceIds.size());
497 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800498 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800499
500 return mNormalDeviceIds[cameraIdInt];
501}
502
503String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
504 Mutex::Autolock lock(mServiceLock);
505 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800506}
507
508Status CameraService::getCameraCharacteristics(const String16& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800509 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700510 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700511 if (!cameraInfo) {
512 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800513 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700514 }
515
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800516 if (!mInitialized) {
517 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800518 return STATUS_ERROR(ERROR_DISCONNECTED,
519 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700520 }
521
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700522 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
523 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
524 "characteristics for system only device %s: ", String8(cameraId).string());
525 }
526
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800527 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800528
Emilian Peevf53f66e2017-04-11 14:29:43 +0100529 status_t res = mCameraProviderManager->getCameraCharacteristics(
530 String8(cameraId).string(), cameraInfo);
531 if (res != OK) {
532 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
533 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
534 strerror(-res), res);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700535 }
Zhijun He2b59be82013-09-25 10:14:30 -0700536
Jayant Chowdhary12361932018-08-27 14:46:13 -0700537 int callingPid = CameraThreadState::getCallingPid();
538 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100539 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700540 // If it's not calling from cameraserver, check the permission only if
541 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
542 // it would've already been checked in shouldRejectSystemCameraConnection.
Emilian Peeve20c6372018-08-14 18:45:53 +0100543 if ((callingPid != getpid()) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700544 (getSystemCameraKind(String8(cameraId)) != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
545 !checkPermission(sCameraPermission, callingPid, callingUid)) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100546 res = cameraInfo->removePermissionEntries(
547 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
548 &tagsRemoved);
549 if (res != OK) {
550 cameraInfo->clear();
551 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
552 " characteristics needing camera permission for device %s: %s (%d)",
553 String8(cameraId).string(), strerror(-res), res);
554 }
555 }
556
557 if (!tagsRemoved.empty()) {
558 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
559 tagsRemoved.data(), tagsRemoved.size());
560 if (res != OK) {
561 cameraInfo->clear();
562 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
563 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
564 strerror(-res), res);
565 }
566 }
567
Zhijun He2b59be82013-09-25 10:14:30 -0700568 return ret;
569}
570
Ruben Brunkcc776712015-02-17 20:18:47 -0800571String8 CameraService::getFormattedCurrentTime() {
572 time_t now = time(nullptr);
573 char formattedTime[64];
574 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
575 return String8(formattedTime);
576}
577
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800578Status CameraService::getCameraVendorTagDescriptor(
579 /*out*/
580 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700581 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800582 if (!mInitialized) {
583 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800584 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800585 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800586 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
587 if (globalDescriptor != nullptr) {
588 *desc = *(globalDescriptor.get());
589 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800590 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800591}
592
Emilian Peev71c73a22017-03-21 16:35:51 +0000593Status CameraService::getCameraVendorTagCache(
594 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
595 ATRACE_CALL();
596 if (!mInitialized) {
597 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
598 return STATUS_ERROR(ERROR_DISCONNECTED,
599 "Camera subsystem not available");
600 }
601 sp<VendorTagDescriptorCache> globalCache =
602 VendorTagDescriptorCache::getGlobalVendorTagCache();
603 if (globalCache != nullptr) {
604 *cache = *(globalCache.get());
605 }
606 return Status::ok();
607}
608
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800609int CameraService::getDeviceVersion(const String8& cameraId, int* facing) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700610 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800611
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800612 int deviceVersion = 0;
613
Emilian Peevf53f66e2017-04-11 14:29:43 +0100614 status_t res;
615 hardware::hidl_version maxVersion{0,0};
616 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
617 &maxVersion);
618 if (res != OK) return -1;
619 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800620
Emilian Peevf53f66e2017-04-11 14:29:43 +0100621 hardware::CameraInfo info;
622 if (facing) {
623 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800624 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100625 *facing = info.facing;
Igor Murashkin634a5152013-02-20 17:15:11 -0800626 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100627
Igor Murashkin634a5152013-02-20 17:15:11 -0800628 return deviceVersion;
629}
630
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800631Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700632 switch(err) {
633 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800634 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800635 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800636 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
637 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800638 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800639 return STATUS_ERROR(ERROR_DISCONNECTED,
640 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700641 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800642 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
643 "Camera HAL encountered error %d: %s",
644 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700645 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800646}
647
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800648Status CameraService::makeClient(const sp<CameraService>& cameraService,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800649 const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800650 int api1CameraId, int facing, int clientPid, uid_t clientUid, int servicePid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700651 int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
Ruben Brunkcc776712015-02-17 20:18:47 -0800652 /*out*/sp<BasicClient>* client) {
653
Ruben Brunkcc776712015-02-17 20:18:47 -0800654 if (halVersion < 0 || halVersion == deviceVersion) {
655 // Default path: HAL version is unspecified by caller, create CameraClient
656 // based on device version reported by the HAL.
657 switch(deviceVersion) {
658 case CAMERA_DEVICE_API_VERSION_1_0:
659 if (effectiveApiLevel == API_1) { // Camera1 API route
660 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800661 *client = new CameraClient(cameraService, tmp, packageName,
662 api1CameraId, facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700663 getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800664 } else { // Camera2 API route
665 ALOGW("Camera using old HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800666 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800667 "Camera device \"%s\" HAL version %d does not support camera2 API",
668 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800669 }
670 break;
Ruben Brunkcc776712015-02-17 20:18:47 -0800671 case CAMERA_DEVICE_API_VERSION_3_0:
672 case CAMERA_DEVICE_API_VERSION_3_1:
673 case CAMERA_DEVICE_API_VERSION_3_2:
674 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -0700675 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -0700676 case CAMERA_DEVICE_API_VERSION_3_5:
Ruben Brunkcc776712015-02-17 20:18:47 -0800677 if (effectiveApiLevel == API_1) { // Camera1 API route
678 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800679 *client = new Camera2Client(cameraService, tmp, packageName,
680 cameraId, api1CameraId,
681 facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700682 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800683 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800684 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
685 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
686 *client = new CameraDeviceClient(cameraService, tmp, packageName, cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -0800687 facing, clientPid, clientUid, servicePid);
688 }
689 break;
690 default:
691 // Should not be reachable
692 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800693 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800694 "Camera device \"%s\" has unknown HAL version %d",
695 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800696 }
697 } else {
698 // A particular HAL version is requested by caller. Create CameraClient
699 // based on the requested HAL version.
700 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
701 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
702 // Only support higher HAL version device opened as HAL1.0 device.
703 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800704 *client = new CameraClient(cameraService, tmp, packageName,
705 api1CameraId, facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700706 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800707 } else {
708 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
709 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
710 " opened as HAL %x device", halVersion, deviceVersion,
711 CAMERA_DEVICE_API_VERSION_1_0);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800712 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800713 "Camera device \"%s\" (HAL version %d) cannot be opened as HAL version %d",
714 cameraId.string(), deviceVersion, halVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800715 }
716 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800717 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800718}
719
Ruben Brunk6267b532015-04-30 17:44:07 -0700720String8 CameraService::toString(std::set<userid_t> intSet) {
721 String8 s("");
722 bool first = true;
723 for (userid_t i : intSet) {
724 if (first) {
725 s.appendFormat("%d", i);
726 first = false;
727 } else {
728 s.appendFormat(", %d", i);
729 }
730 }
731 return s;
732}
733
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800734int32_t CameraService::mapToInterface(TorchModeStatus status) {
735 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
736 switch (status) {
737 case TorchModeStatus::NOT_AVAILABLE:
738 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
739 break;
740 case TorchModeStatus::AVAILABLE_OFF:
741 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
742 break;
743 case TorchModeStatus::AVAILABLE_ON:
744 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
745 break;
746 default:
747 ALOGW("Unknown new flash status: %d", status);
748 }
749 return serviceStatus;
750}
751
752CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
753 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
754 switch (status) {
755 case CameraDeviceStatus::NOT_PRESENT:
756 serviceStatus = StatusInternal::NOT_PRESENT;
757 break;
758 case CameraDeviceStatus::PRESENT:
759 serviceStatus = StatusInternal::PRESENT;
760 break;
761 case CameraDeviceStatus::ENUMERATING:
762 serviceStatus = StatusInternal::ENUMERATING;
763 break;
764 default:
765 ALOGW("Unknown new HAL device status: %d", status);
766 }
767 return serviceStatus;
768}
769
770int32_t CameraService::mapToInterface(StatusInternal status) {
771 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
772 switch (status) {
773 case StatusInternal::NOT_PRESENT:
774 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
775 break;
776 case StatusInternal::PRESENT:
777 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
778 break;
779 case StatusInternal::ENUMERATING:
780 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
781 break;
782 case StatusInternal::NOT_AVAILABLE:
783 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
784 break;
785 case StatusInternal::UNKNOWN:
786 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
787 break;
788 default:
789 ALOGW("Unknown new internal device status: %d", status);
790 }
791 return serviceStatus;
792}
793
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800794Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -0700795 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700796
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800797 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -0800798 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800799 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800800 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800801 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800802 sp<ICameraClient>{nullptr}, id, cameraId,
803 static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800804 internalPackageName, uid, USE_CALLING_PID,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700805 API_1, /*shimUpdateOnly*/ true, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800806 ).isOk()) {
807 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -0700808 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800809 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700810}
811
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800812Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -0700813 /*out*/
814 CameraParameters* parameters) {
815
816 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
817
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800818 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -0700819
820 if (parameters == NULL) {
821 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800822 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700823 }
824
Ruben Brunkcc776712015-02-17 20:18:47 -0800825 String8 id = String8::format("%d", cameraId);
826
827 // Check if we already have parameters
828 {
829 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700830 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800831 auto cameraState = getCameraState(id);
832 if (cameraState == nullptr) {
833 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800834 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
835 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800836 }
837 CameraParameters p = cameraState->getShimParams();
838 if (!p.isEmpty()) {
839 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800840 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700841 }
842 }
843
Jayant Chowdhary12361932018-08-27 14:46:13 -0700844 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -0800845 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -0700846 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800847 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800848 // Error already logged by callee
849 return ret;
850 }
851
852 // Check for parameters again
853 {
854 // Scope for service lock
855 Mutex::Autolock lock(mServiceLock);
856 auto cameraState = getCameraState(id);
857 if (cameraState == nullptr) {
858 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800859 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
860 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -0700861 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800862 CameraParameters p = cameraState->getShimParams();
863 if (!p.isEmpty()) {
864 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800865 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700866 }
867 }
868
Ruben Brunkcc776712015-02-17 20:18:47 -0800869 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
870 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800871 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700872}
873
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800874// Can camera service trust the caller based on the calling UID?
875static bool isTrustedCallingUid(uid_t uid) {
876 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -0700877 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800878 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -0700879 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800880 return true;
881 default:
882 return false;
883 }
884}
885
Nicholas Sauera3620332019-04-03 14:05:17 -0700886static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
887 PermissionController pc;
888 uid = pc.getPackageUid(packageName, 0);
889 if (uid <= 0) {
890 ALOGE("Unknown package: '%s'", String8(packageName).string());
891 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
892 return BAD_VALUE;
893 }
894
895 if (userId < 0) {
896 ALOGE("Invalid user: %d", userId);
897 dprintf(err, "Invalid user: %d\n", userId);
898 return BAD_VALUE;
899 }
900
901 uid = multiuser_get_uid(userId, uid);
902 return NO_ERROR;
903}
904
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800905Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -0700906 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
907 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -0500908
Alex Deymo9c2a2c22016-08-25 11:59:14 -0700909#ifdef __BRILLO__
910 UNUSED(clientName8);
911 UNUSED(clientUid);
912 UNUSED(clientPid);
913 UNUSED(originalClientPid);
914#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -0700915 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
916 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800917 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -0800918 return allowed;
919 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -0700920#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -0800921
Jayant Chowdhary12361932018-08-27 14:46:13 -0700922 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800923
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800924 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800925 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
926 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800927 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
928 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -0700929 }
930
Ruben Brunkcc776712015-02-17 20:18:47 -0800931 if (getCameraState(cameraId) == nullptr) {
932 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
933 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800934 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
935 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700936 }
937
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800938 status_t err = checkIfDeviceIsUsable(cameraId);
939 if (err != NO_ERROR) {
940 switch(err) {
941 case -ENODEV:
942 case -EBUSY:
943 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
944 "No camera device with ID \"%s\" currently available", cameraId.string());
945 default:
946 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
947 "Unknown error connecting to ID \"%s\"", cameraId.string());
948 }
949 }
950 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -0800951}
952
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800953Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -0700954 const String8& clientName8, int& clientUid, int& clientPid,
955 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -0700956 int callingPid = CameraThreadState::getCallingPid();
957 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700958
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800959 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -0700960 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800961 clientUid = callingUid;
962 } else if (!isTrustedCallingUid(callingUid)) {
963 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
964 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800965 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
966 "Untrusted caller (calling PID %d, UID %d) trying to "
967 "forward camera access to camera %s for client %s (PID %d, UID %d)",
968 callingPid, callingUid, cameraId.string(),
969 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700970 }
971
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800972 // Check if we can trust clientPid
973 if (clientPid == USE_CALLING_PID) {
974 clientPid = callingPid;
975 } else if (!isTrustedCallingUid(callingUid)) {
976 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
977 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800978 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
979 "Untrusted caller (calling PID %d, UID %d) trying to "
980 "forward camera access to camera %s for client %s (PID %d, UID %d)",
981 callingPid, callingUid, cameraId.string(),
982 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800983 }
984
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700985 if (shouldRejectSystemCameraConnection(cameraId)) {
986 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
987 cameraId.c_str());
988 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
989 "available", cameraId.string());
990 }
991 // If it's not calling from cameraserver, check the permission if the
992 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
993 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800994 if (callingPid != getpid() &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700995 (getSystemCameraKind(cameraId) != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
996 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800997 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800998 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
999 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1000 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001001 }
1002
Svet Ganova453d0d2018-01-11 15:37:58 -08001003 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001004 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001005 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001006 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1007 clientPid, clientUid);
1008 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001009 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1010 "calling UID %d proc state %" PRId32 ")",
1011 clientName8.string(), clientUid, clientPid, cameraId.string(),
1012 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001013 }
1014
Michael Grooverd1d435a2018-12-18 17:39:42 -08001015 // If sensor privacy is enabled then prevent access to the camera
1016 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1017 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1018 return STATUS_ERROR_FMT(ERROR_DISABLED,
1019 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1020 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1021 }
1022
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001023 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1024 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001025 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001026 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001027
Ruben Brunk6267b532015-04-30 17:44:07 -07001028 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001029
Ruben Brunka8ca9152015-04-07 14:23:40 -07001030 // Only allow clients who are being used by the current foreground device user, unless calling
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001031 // from our own process OR the caller is using the cameraserver's HIDL interface.
1032 if (!hardware::IPCThreadState::self()->isServingCall() && callingPid != getpid() &&
1033 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001034 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1035 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1036 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001037 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1038 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1039 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001040 }
1041
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001042 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001043}
1044
1045status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1046 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001047 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001048 if (cameraState == nullptr) {
1049 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1050 cameraId.string());
1051 return -ENODEV;
1052 }
1053
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001054 StatusInternal currentStatus = cameraState->getStatus();
1055 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001056 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1057 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001058 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001059 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001060 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1061 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001062 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001063 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001064
Ruben Brunkcc776712015-02-17 20:18:47 -08001065 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001066}
1067
Ruben Brunkcc776712015-02-17 20:18:47 -08001068void CameraService::finishConnectLocked(const sp<BasicClient>& client,
1069 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001070
Ruben Brunkcc776712015-02-17 20:18:47 -08001071 // Make a descriptor for the incoming client
1072 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
1073 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1074
1075 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1076 String8(client->getPackageName()));
1077
1078 if (evicted.size() > 0) {
1079 // This should never happen - clients should already have been removed in disconnect
1080 for (auto& i : evicted) {
1081 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1082 __FUNCTION__, i->getKey().string());
1083 }
1084
1085 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1086 __FUNCTION__);
1087 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001088
1089 // And register a death notification for the client callback. Do
1090 // this last to avoid Binder policy where a nested Binder
1091 // transaction might be pre-empted to service the client death
1092 // notification if the client process dies before linkToDeath is
1093 // invoked.
1094 sp<IBinder> remoteCallback = client->getRemote();
1095 if (remoteCallback != nullptr) {
1096 remoteCallback->linkToDeath(this);
1097 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001098}
1099
1100status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1101 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
1102 /*out*/
1103 sp<BasicClient>* client,
1104 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001105 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001106 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001107 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001108 DescriptorPtr clientDescriptor;
1109 {
1110 if (effectiveApiLevel == API_1) {
1111 // If we are using API1, any existing client for this camera ID with the same remote
1112 // should be returned rather than evicted to allow MediaRecorder to work properly.
1113
1114 auto current = mActiveClientManager.get(cameraId);
1115 if (current != nullptr) {
1116 auto clientSp = current->getValue();
1117 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001118 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1119 ALOGW("CameraService connect called from same client, but with a different"
1120 " API level, evicting prior client...");
1121 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001122 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001123 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001124 *client = clientSp;
1125 return NO_ERROR;
1126 }
1127 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001128 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001129 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001130
Ruben Brunkcc776712015-02-17 20:18:47 -08001131 // Get current active client PIDs
1132 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1133 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001134
Emilian Peev8131a262017-02-01 12:33:43 +00001135 std::vector<int> priorityScores(ownerPids.size());
1136 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001137
Emilian Peev8131a262017-02-01 12:33:43 +00001138 // Get priority scores of all active PIDs
1139 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1140 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1141 /*out*/&priorityScores[0]);
1142 if (err != OK) {
1143 ALOGE("%s: Priority score query failed: %d",
1144 __FUNCTION__, err);
1145 return err;
1146 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001147
Ruben Brunkcc776712015-02-17 20:18:47 -08001148 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001149 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001150 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001151 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001152 resource_policy::ClientPriority(priorityScores[i], states[i],
1153 /* isVendorClient won't get copied over*/ false));
Ruben Brunkcc776712015-02-17 20:18:47 -08001154 }
1155 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001156
Ruben Brunkcc776712015-02-17 20:18:47 -08001157 // Get state for the given cameraId
1158 auto state = getCameraState(cameraId);
1159 if (state == nullptr) {
1160 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1161 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001162 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001163 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001164 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001165
1166 // Make descriptor for incoming client
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001167 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001168 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1169 state->getConflicting(),
Emilian Peev8131a262017-02-01 12:33:43 +00001170 priorityScores[priorityScores.size() - 1],
1171 clientPid,
1172 states[states.size() - 1]);
Ruben Brunkcc776712015-02-17 20:18:47 -08001173
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001174 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1175
Ruben Brunkcc776712015-02-17 20:18:47 -08001176 // Find clients that would be evicted
1177 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1178
1179 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1180 // background, so we cannot do evictions
1181 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1182 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1183 " priority).", clientPid);
1184
1185 sp<BasicClient> clientSp = clientDescriptor->getValue();
1186 String8 curTime = getFormattedCurrentTime();
1187 auto incompatibleClients =
1188 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1189
1190 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001191 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001192 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001193 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001194
1195 for (auto& i : incompatibleClients) {
1196 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001197 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1198 i->getKey().string(),
1199 String8{i->getValue()->getPackageName()}.string(),
1200 i->getOwnerId(), i->getPriority().getScore(),
1201 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001202 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001203 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001204 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001205 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001206 }
1207
1208 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001209 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001210 mEventLog.add(msg);
1211
1212 return -EBUSY;
1213 }
1214
1215 for (auto& i : evicted) {
1216 sp<BasicClient> clientSp = i->getValue();
1217 if (clientSp.get() == nullptr) {
1218 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1219
1220 // TODO: Remove this
1221 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1222 __FUNCTION__);
1223 mActiveClientManager.remove(i);
1224 continue;
1225 }
1226
1227 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1228 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001229 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001230
Ruben Brunkcc776712015-02-17 20:18:47 -08001231 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001232 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001233 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1234 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001235 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001236 i->getOwnerId(), i->getPriority().getScore(),
1237 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001238 packageName.string(), clientPid, clientPriority.getScore(),
1239 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001240
1241 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001242 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001243 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001244 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001245 }
1246
Ruben Brunkcc776712015-02-17 20:18:47 -08001247 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1248 // other clients from connecting in mServiceLockWrapper if held
1249 mServiceLock.unlock();
1250
1251 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001252 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001253
1254 // Destroy evicted clients
1255 for (auto& i : evictedClients) {
1256 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001257 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001258 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001259
Jayant Chowdhary12361932018-08-27 14:46:13 -07001260 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001261
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001262 for (const auto& i : evictedClients) {
1263 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1264 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1265 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1266 if (ret == TIMED_OUT) {
1267 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1268 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1269 mActiveClientManager.toString().string());
1270 return -EBUSY;
1271 }
1272 if (ret != NO_ERROR) {
1273 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1274 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1275 ret, mActiveClientManager.toString().string());
1276 return ret;
1277 }
1278 }
1279
1280 evictedClients.clear();
1281
Ruben Brunkcc776712015-02-17 20:18:47 -08001282 // Once clients have been disconnected, relock
1283 mServiceLock.lock();
1284
1285 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1286 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1287 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001288 }
1289
Ruben Brunkcc776712015-02-17 20:18:47 -08001290 *partial = clientDescriptor;
1291 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001292}
1293
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001294Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001295 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001296 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001297 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001298 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001299 int clientPid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001300 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001301 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001302
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001303 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001304 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001305
1306 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001307 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001308 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001309 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, clientUid, clientPid, API_1,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001310 /*shimUpdateOnly*/ false, /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001311
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001312 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001313 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001314 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001315 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001316 }
1317
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001318 *device = client;
1319 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001320}
1321
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001322Status CameraService::connectLegacy(
Zhijun Heb10cdad2014-06-16 16:38:35 -07001323 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001324 int api1CameraId, int halVersion,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001325 const String16& clientPackageName,
Zhijun Heb10cdad2014-06-16 16:38:35 -07001326 int clientUid,
1327 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001328 sp<ICamera>* device) {
Zhijun Heb10cdad2014-06-16 16:38:35 -07001329
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001330 ATRACE_CALL();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001331 String8 id = cameraIdIntToStr(api1CameraId);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001332
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001333 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001334 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001335 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId, halVersion,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001336 clientPackageName, clientUid, USE_CALLING_PID, API_1, /*shimUpdateOnly*/ false,
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001337 /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001338
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001339 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001340 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001341 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001342 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001343 }
1344
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001345 *device = client;
1346 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001347}
1348
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001349static bool hasPermissionsForSystemCamera(int callingPid, int callingUid) {
1350 return checkPermission(sSystemCameraPermission, callingPid, callingUid) &&
1351 checkPermission(sCameraPermission, callingPid, callingUid);
1352}
1353
1354bool CameraService::shouldSkipStatusUpdates(const String8& cameraId, bool isVendorListener,
1355 int clientPid, int clientUid) const {
1356 SystemCameraKind systemCameraKind = getSystemCameraKind(cameraId);
1357 // If the client is not a vendor client, don't add listener if
1358 // a) the camera is a publicly hidden secure camera OR
1359 // b) the camera is a system only camera and the client doesn't
1360 // have android.permission.SYSTEM_CAMERA permissions.
1361 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1362 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1363 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001364 return true;
1365 }
1366 return false;
1367}
1368
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001369bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1370 // Rules for rejection:
1371 // 1) If cameraserver tries to access this camera device, accept the
1372 // connection.
1373 // 2) The camera device is a publicly hidden secure camera device AND some
1374 // component is trying to access it on a non-hwbinder thread (generally a non HAL client),
1375 // reject it.
1376 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1377 // and the serving thread is a non hwbinder thread, the client must have
1378 // android.permission.SYSTEM_CAMERA permissions to connect.
1379
1380 int cPid = CameraThreadState::getCallingPid();
1381 int cUid = CameraThreadState::getCallingUid();
1382 SystemCameraKind systemCameraKind = getSystemCameraKind(cameraId);
1383
1384 // (1) Cameraserver trying to connect, accept.
1385 if (CameraThreadState::getCallingPid() == getpid()) {
1386 return false;
1387 }
1388 // (2)
1389 if (!hardware::IPCThreadState::self()->isServingCall() &&
1390 systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
1391 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1392 return true;
1393 }
1394 // (3) Here we only check for permissions if it is a system only camera device. This is since
1395 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1396 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1397 // same behavior for system camera devices.
1398 if (!hardware::IPCThreadState::self()->isServingCall() &&
1399 systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1400 !hasPermissionsForSystemCamera(cPid, cUid)) {
1401 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1402 cameraId.c_str());
1403 return true;
1404 }
1405
1406 return false;
1407}
1408
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001409Status CameraService::connectDevice(
1410 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001411 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001412 const String16& clientPackageName,
Ruben Brunkcc776712015-02-17 20:18:47 -08001413 int clientUid,
1414 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001415 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001416
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001417 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001418 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001419 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001420 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001421 String16 clientPackageNameAdj = clientPackageName;
1422 if (hardware::IPCThreadState::self()->isServingCall()) {
1423 std::string vendorClient =
1424 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1425 clientPackageNameAdj = String16(vendorClient.c_str());
1426 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001427 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001428 /*api1CameraId*/-1,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001429 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageNameAdj,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001430 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001431
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001432 if(!ret.isOk()) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001433 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageNameAdj),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001434 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001435 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001436 }
1437
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001438 *device = client;
1439 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001440}
1441
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001442template<class CALLBACK, class CLIENT>
1443Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001444 int api1CameraId, int halVersion, const String16& clientPackageName, int clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001445 int clientPid, apiLevel effectiveApiLevel, bool shimUpdateOnly,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001446 /*out*/sp<CLIENT>& device) {
1447 binder::Status ret = binder::Status::ok();
1448
1449 String8 clientName8(clientPackageName);
1450
1451 int originalClientPid = 0;
1452
1453 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) for HAL version %s and "
1454 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
1455 (halVersion == -1) ? "default" : std::to_string(halVersion).c_str(),
1456 static_cast<int>(effectiveApiLevel));
1457
1458 sp<CLIENT> client = nullptr;
1459 {
1460 // Acquire mServiceLock and prevent other clients from connecting
1461 std::unique_ptr<AutoConditionLock> lock =
1462 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1463
1464 if (lock == nullptr) {
1465 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1466 , clientPid);
1467 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1468 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1469 cameraId.string(), clientName8.string(), clientPid);
1470 }
1471
1472 // Enforce client permissions and do basic sanity checks
1473 if(!(ret = validateConnectLocked(cameraId, clientName8,
1474 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1475 return ret;
1476 }
1477
1478 // Check the shim parameters after acquiring lock, if they have already been updated and
1479 // we were doing a shim update, return immediately
1480 if (shimUpdateOnly) {
1481 auto cameraState = getCameraState(cameraId);
1482 if (cameraState != nullptr) {
1483 if (!cameraState->getShimParams().isEmpty()) return ret;
1484 }
1485 }
1486
1487 status_t err;
1488
1489 sp<BasicClient> clientTmp = nullptr;
1490 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1491 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
1492 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
1493 /*out*/&partial)) != NO_ERROR) {
1494 switch (err) {
1495 case -ENODEV:
1496 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1497 "No camera device with ID \"%s\" currently available",
1498 cameraId.string());
1499 case -EBUSY:
1500 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1501 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1502 cameraId.string());
1503 default:
1504 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1505 "Unexpected error %s (%d) opening camera \"%s\"",
1506 strerror(-err), err, cameraId.string());
1507 }
1508 }
1509
1510 if (clientTmp.get() != nullptr) {
1511 // Handle special case for API1 MediaRecorder where the existing client is returned
1512 device = static_cast<CLIENT*>(clientTmp.get());
1513 return ret;
1514 }
1515
1516 // give flashlight a chance to close devices if necessary.
1517 mFlashlight->prepareDeviceOpen(cameraId);
1518
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001519 int facing = -1;
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001520 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001521 if (facing == -1) {
1522 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1523 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1524 "Unable to get camera device \"%s\" facing", cameraId.string());
1525 }
1526
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001527 sp<BasicClient> tmp = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001528 if(!(ret = makeClient(this, cameraCb, clientPackageName,
1529 cameraId, api1CameraId, facing,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001530 clientPid, clientUid, getpid(),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001531 halVersion, deviceVersion, effectiveApiLevel,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001532 /*out*/&tmp)).isOk()) {
1533 return ret;
1534 }
1535 client = static_cast<CLIENT*>(tmp.get());
1536
1537 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1538 __FUNCTION__);
1539
Emilian Peevbd8c5032018-02-14 23:05:40 +00001540 err = client->initialize(mCameraProviderManager, mMonitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001541 if (err != OK) {
1542 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001543 // Errors could be from the HAL module open call or from AppOpsManager
1544 switch(err) {
1545 case BAD_VALUE:
1546 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1547 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1548 case -EBUSY:
1549 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1550 "Camera \"%s\" is already open", cameraId.string());
1551 case -EUSERS:
1552 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1553 "Too many cameras already open, cannot open camera \"%s\"",
1554 cameraId.string());
1555 case PERMISSION_DENIED:
1556 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1557 "No permission to open camera \"%s\"", cameraId.string());
1558 case -EACCES:
1559 return STATUS_ERROR_FMT(ERROR_DISABLED,
1560 "Camera \"%s\" disabled by policy", cameraId.string());
1561 case -ENODEV:
1562 default:
1563 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1564 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1565 strerror(-err), err);
1566 }
1567 }
1568
1569 // Update shim paremeters for legacy clients
1570 if (effectiveApiLevel == API_1) {
1571 // Assume we have always received a Client subclass for API1
1572 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1573 String8 rawParams = shimClient->getParameters();
1574 CameraParameters params(rawParams);
1575
1576 auto cameraState = getCameraState(cameraId);
1577 if (cameraState != nullptr) {
1578 cameraState->setShimParams(params);
1579 } else {
1580 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1581 __FUNCTION__, cameraId.string());
1582 }
1583 }
1584
1585 if (shimUpdateOnly) {
1586 // If only updating legacy shim parameters, immediately disconnect client
1587 mServiceLock.unlock();
1588 client->disconnect();
1589 mServiceLock.lock();
1590 } else {
1591 // Otherwise, add client to active clients list
1592 finishConnectLocked(client, partial);
1593 }
1594 } // lock is destroyed, allow further connect calls
1595
1596 // Important: release the mutex here so the client can call back into the service from its
1597 // destructor (can be at the end of the call)
1598 device = client;
1599 return ret;
1600}
1601
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001602Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001603 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001604 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001605
1606 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001607 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001608 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001609 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1610 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001611 }
1612
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001613 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07001614 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001615
1616 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001617 auto state = getCameraState(id);
1618 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001619 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001620 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1621 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001622 }
1623
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001624 StatusInternal cameraStatus = state->getStatus();
1625 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001626 cameraStatus != StatusInternal::NOT_AVAILABLE) {
1627 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001628 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1629 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001630 }
1631
1632 {
1633 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001634 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001635 status_t err = getTorchStatusLocked(id, &status);
1636 if (err != OK) {
1637 if (err == NAME_NOT_FOUND) {
1638 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1639 "Camera \"%s\" does not have a flash unit", id.string());
1640 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001641 ALOGE("%s: getting current torch status failed for camera %s",
1642 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001643 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1644 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
1645 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001646 }
1647
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001648 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001649 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001650 ALOGE("%s: torch mode of camera %s is not available because "
1651 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001652 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1653 "Torch for camera \"%s\" is not available due to an existing camera user",
1654 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001655 } else {
1656 ALOGE("%s: torch mode of camera %s is not available due to "
1657 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001658 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1659 "Torch for camera \"%s\" is not available due to insufficient resources",
1660 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001661 }
1662 }
1663 }
1664
Ruben Brunk99e69712015-05-26 17:25:07 -07001665 {
1666 // Update UID map - this is used in the torch status changed callbacks, so must be done
1667 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001668 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001669 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1670 mTorchUidMap[id].first = uid;
1671 mTorchUidMap[id].second = uid;
1672 } else {
1673 // Set the pending UID
1674 mTorchUidMap[id].first = uid;
1675 }
1676 }
1677
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001678 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001679
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001680 if (err != OK) {
1681 int32_t errorCode;
1682 String8 msg;
1683 switch (err) {
1684 case -ENOSYS:
1685 msg = String8::format("Camera \"%s\" has no flashlight",
1686 id.string());
1687 errorCode = ERROR_ILLEGAL_ARGUMENT;
1688 break;
1689 default:
1690 msg = String8::format(
1691 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1692 id.string(), enabled, strerror(-err), err);
1693 errorCode = ERROR_INVALID_OPERATION;
1694 }
1695 ALOGE("%s: %s", __FUNCTION__, msg.string());
1696 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001697 }
1698
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001699 {
1700 // update the link to client's death
1701 Mutex::Autolock al(mTorchClientMapMutex);
1702 ssize_t index = mTorchClientMap.indexOfKey(id);
1703 if (enabled) {
1704 if (index == NAME_NOT_FOUND) {
1705 mTorchClientMap.add(id, clientBinder);
1706 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001707 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001708 mTorchClientMap.replaceValueAt(index, clientBinder);
1709 }
1710 clientBinder->linkToDeath(this);
1711 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001712 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001713 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001714 }
1715
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07001716 int clientPid = CameraThreadState::getCallingPid();
1717 const char *id_cstr = id.c_str();
1718 const char *torchState = enabled ? "on" : "off";
1719 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
1720 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001721 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001722}
1723
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001724Status CameraService::notifySystemEvent(int32_t eventId,
1725 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001726 const int pid = CameraThreadState::getCallingPid();
1727 const int selfPid = getpid();
1728
1729 // Permission checks
1730 if (pid != selfPid) {
1731 // Ensure we're being called by system_server, or similar process with
1732 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001733 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001734 const int uid = CameraThreadState::getCallingUid();
1735 ALOGE("Permission Denial: cannot send updates to camera service about system"
1736 " events from pid=%d, uid=%d", pid, uid);
1737 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09001738 "No permission to send updates to camera service about system events"
1739 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001740 }
1741 }
1742
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001743 ATRACE_CALL();
1744
Ruben Brunk36597b22015-03-20 22:15:57 -07001745 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001746 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001747 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07001748 // from a system server crash
1749 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08001750 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001751 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07001752 break;
1753 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001754 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07001755 default: {
1756 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1757 eventId);
1758 break;
1759 }
1760 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001761 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07001762}
1763
Emilian Peev53722fa2019-02-22 17:47:20 -08001764void CameraService::notifyMonitoredUids() {
1765 Mutex::Autolock lock(mStatusListenerLock);
1766
1767 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001768 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08001769 if (!ret.isOk()) {
1770 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
1771 ret.exceptionCode());
1772 }
1773 }
1774}
1775
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08001776Status CameraService::notifyDeviceStateChange(int64_t newState) {
1777 const int pid = CameraThreadState::getCallingPid();
1778 const int selfPid = getpid();
1779
1780 // Permission checks
1781 if (pid != selfPid) {
1782 // Ensure we're being called by system_server, or similar process with
1783 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001784 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08001785 const int uid = CameraThreadState::getCallingUid();
1786 ALOGE("Permission Denial: cannot send updates to camera service about device"
1787 " state changes from pid=%d, uid=%d", pid, uid);
1788 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1789 "No permission to send updates to camera service about device state"
1790 " changes from pid=%d, uid=%d", pid, uid);
1791 }
1792 }
1793
1794 ATRACE_CALL();
1795
1796 using hardware::camera::provider::V2_5::DeviceState;
1797 hardware::hidl_bitfield<DeviceState> newDeviceState{};
1798 if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
1799 newDeviceState |= DeviceState::BACK_COVERED;
1800 }
1801 if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
1802 newDeviceState |= DeviceState::FRONT_COVERED;
1803 }
1804 if (newState & ICameraService::DEVICE_STATE_FOLDED) {
1805 newDeviceState |= DeviceState::FOLDED;
1806 }
1807 // Only map vendor bits directly
1808 uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
1809 newDeviceState |= vendorBits;
1810
1811 ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
1812 Mutex::Autolock l(mServiceLock);
1813 mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
1814
1815 return Status::ok();
1816}
1817
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001818Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
1819 /*out*/
1820 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001821 return addListenerHelper(listener, cameraStatuses);
1822}
1823
1824Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
1825 /*out*/
1826 std::vector<hardware::CameraStatus> *cameraStatuses,
1827 bool isVendorListener) {
1828
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001829 ATRACE_CALL();
1830
Igor Murashkinbfc99152013-02-27 12:55:20 -08001831 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08001832
Ruben Brunk3450ba72015-06-16 11:00:37 -07001833 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001834 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001835 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001836 }
1837
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001838 auto clientUid = CameraThreadState::getCallingUid();
1839 auto clientPid = CameraThreadState::getCallingPid();
1840
Igor Murashkinbfc99152013-02-27 12:55:20 -08001841 Mutex::Autolock lock(mServiceLock);
1842
Ruben Brunkcc776712015-02-17 20:18:47 -08001843 {
1844 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08001845 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001846 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001847 ALOGW("%s: Tried to add listener %p which was already subscribed",
1848 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001849 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08001850 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001851 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001852
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001853 sp<ServiceListener> serviceListener =
1854 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08001855 auto ret = serviceListener->initialize();
1856 if (ret != NO_ERROR) {
1857 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
1858 strerror(-ret), ret);
1859 ALOGE("%s: %s", __FUNCTION__, msg.string());
1860 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
1861 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001862 // The listener still needs to be added to the list of listeners, regardless of what
1863 // permissions the listener process has / whether it is a vendor listener. Since it might be
1864 // eligible to listen to other camera ids.
1865 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08001866 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08001867 }
1868
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001869 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07001870 {
Ruben Brunkcc776712015-02-17 20:18:47 -08001871 Mutex::Autolock lock(mCameraStatesLock);
1872 for (auto& i : mCameraStates) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001873 if (shouldSkipStatusUpdates(i.first, isVendorListener, clientPid, clientUid)) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001874 ALOGV("Cannot add public listener for hidden system-only %s for pid %d",
1875 i.first.c_str(), CameraThreadState::getCallingPid());
1876 continue;
1877 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001878 cameraStatuses->emplace_back(i.first, mapToInterface(i.second->getStatus()));
Igor Murashkincba2c162013-03-20 15:56:31 -07001879 }
1880 }
1881
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001882 /*
1883 * Immediately signal current torch status to this listener only
1884 * This may be a subset of all the devices, so don't include it in the response directly
1885 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001886 {
1887 Mutex::Autolock al(mTorchStatusMutex);
1888 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001889 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001890 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001891 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001892 }
1893
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001894 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08001895}
Ruben Brunkcc776712015-02-17 20:18:47 -08001896
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001897Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001898 ATRACE_CALL();
1899
Igor Murashkinbfc99152013-02-27 12:55:20 -08001900 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
1901
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001902 if (listener == 0) {
1903 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001904 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001905 }
1906
Igor Murashkinbfc99152013-02-27 12:55:20 -08001907 Mutex::Autolock lock(mServiceLock);
1908
Ruben Brunkcc776712015-02-17 20:18:47 -08001909 {
1910 Mutex::Autolock lock(mStatusListenerLock);
1911 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001912 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
1913 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
1914 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08001915 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001916 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001917 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001918 }
1919 }
1920
1921 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
1922 __FUNCTION__, listener.get());
1923
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001924 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08001925}
1926
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001927Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001928
1929 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001930 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1931
1932 if (parameters == NULL) {
1933 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001934 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001935 }
1936
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001937 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001938
1939 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001940 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07001941 // Error logged by caller
1942 return ret;
1943 }
1944
1945 String8 shimParamsString8 = shimParams.flatten();
1946 String16 shimParamsString16 = String16(shimParamsString8);
1947
1948 *parameters = shimParamsString16;
1949
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001950 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001951}
1952
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001953Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
1954 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001955 ATRACE_CALL();
1956
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001957 const String8 id = String8(cameraId);
1958
1959 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001960
1961 switch (apiVersion) {
1962 case API_VERSION_1:
1963 case API_VERSION_2:
1964 break;
1965 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001966 String8 msg = String8::format("Unknown API version %d", apiVersion);
1967 ALOGE("%s: %s", __FUNCTION__, msg.string());
1968 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001969 }
1970
Emilian Peev28ad2ea2017-02-07 16:14:32 +00001971 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07001972 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001973 case CAMERA_DEVICE_API_VERSION_1_0:
1974 case CAMERA_DEVICE_API_VERSION_3_0:
1975 case CAMERA_DEVICE_API_VERSION_3_1:
1976 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001977 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
1978 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001979 *isSupported = false;
1980 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001981 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
1982 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001983 *isSupported = true;
1984 }
1985 break;
1986 case CAMERA_DEVICE_API_VERSION_3_2:
1987 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07001988 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07001989 case CAMERA_DEVICE_API_VERSION_3_5:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001990 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
1991 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001992 *isSupported = true;
1993 break;
1994 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001995 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001996 ALOGE("%s: %s", __FUNCTION__, msg.string());
1997 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001998 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001999 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002000 String8 msg = String8::format("Unknown device version %x for device %s",
2001 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002002 ALOGE("%s: %s", __FUNCTION__, msg.string());
2003 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2004 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002005 }
2006
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002007 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002008}
2009
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002010Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2011 /*out*/ bool *isSupported) {
2012 ATRACE_CALL();
2013
2014 const String8 id = String8(cameraId);
2015
2016 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2017 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2018
2019 return Status::ok();
2020}
2021
Ruben Brunkcc776712015-02-17 20:18:47 -08002022void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002023 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002024 for (auto& i : mActiveClientManager.getAll()) {
2025 auto clientSp = i->getValue();
2026 if (clientSp.get() == client) {
2027 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002028 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002029 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002030}
2031
Ruben Brunkcc776712015-02-17 20:18:47 -08002032bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002033 bool ret = false;
2034 {
2035 // Acquire mServiceLock and prevent other clients from connecting
2036 std::unique_ptr<AutoConditionLock> lock =
2037 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002038
Igor Murashkin634a5152013-02-20 17:15:11 -08002039
Ruben Brunkcc776712015-02-17 20:18:47 -08002040 std::vector<sp<BasicClient>> evicted;
2041 for (auto& i : mActiveClientManager.getAll()) {
2042 auto clientSp = i->getValue();
2043 if (clientSp.get() == nullptr) {
2044 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2045 mActiveClientManager.remove(i);
2046 continue;
2047 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002048 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002049 mActiveClientManager.remove(i);
2050 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002051
Ruben Brunkcc776712015-02-17 20:18:47 -08002052 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002053 clientSp->notifyError(
2054 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002055 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002056 }
2057 }
2058
Ruben Brunkcc776712015-02-17 20:18:47 -08002059 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2060 // other clients from connecting in mServiceLockWrapper if held
2061 mServiceLock.unlock();
2062
Ruben Brunk36597b22015-03-20 22:15:57 -07002063 // Do not clear caller identity, remote caller should be client proccess
2064
Ruben Brunkcc776712015-02-17 20:18:47 -08002065 for (auto& i : evicted) {
2066 if (i.get() != nullptr) {
2067 i->disconnect();
2068 ret = true;
2069 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002070 }
2071
Ruben Brunkcc776712015-02-17 20:18:47 -08002072 // Reacquire mServiceLock
2073 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002074
Ruben Brunkcc776712015-02-17 20:18:47 -08002075 } // lock is destroyed, allow further connect calls
2076
2077 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002078}
2079
Ruben Brunkcc776712015-02-17 20:18:47 -08002080std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2081 const String8& cameraId) const {
2082 std::shared_ptr<CameraState> state;
2083 {
2084 Mutex::Autolock lock(mCameraStatesLock);
2085 auto iter = mCameraStates.find(cameraId);
2086 if (iter != mCameraStates.end()) {
2087 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002088 }
2089 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002090 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002091}
2092
Ruben Brunkcc776712015-02-17 20:18:47 -08002093sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2094 // Remove from active clients list
2095 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2096 if (clientDescriptorPtr == nullptr) {
2097 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2098 cameraId.string());
2099 return sp<BasicClient>{nullptr};
2100 }
2101
2102 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07002103}
2104
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002105void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002106 // Acquire mServiceLock and prevent other clients from connecting
2107 std::unique_ptr<AutoConditionLock> lock =
2108 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2109
Ruben Brunk6267b532015-04-30 17:44:07 -07002110 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002111 for (size_t i = 0; i < newUserIds.size(); i++) {
2112 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002113 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002114 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002115 return;
2116 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002117 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002118 }
2119
Ruben Brunka8ca9152015-04-07 14:23:40 -07002120
Ruben Brunk6267b532015-04-30 17:44:07 -07002121 if (newAllowedUsers == mAllowedUsers) {
2122 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2123 return;
2124 }
2125
2126 logUserSwitch(mAllowedUsers, newAllowedUsers);
2127
2128 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002129
2130 // Current user has switched, evict all current clients.
2131 std::vector<sp<BasicClient>> evicted;
2132 for (auto& i : mActiveClientManager.getAll()) {
2133 auto clientSp = i->getValue();
2134
2135 if (clientSp.get() == nullptr) {
2136 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2137 continue;
2138 }
2139
Ruben Brunk6267b532015-04-30 17:44:07 -07002140 // Don't evict clients that are still allowed.
2141 uid_t clientUid = clientSp->getClientUid();
2142 userid_t clientUserId = multiuser_get_user_id(clientUid);
2143 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2144 continue;
2145 }
2146
Ruben Brunk36597b22015-03-20 22:15:57 -07002147 evicted.push_back(clientSp);
2148
2149 String8 curTime = getFormattedCurrentTime();
2150
2151 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2152 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002153
Ruben Brunk36597b22015-03-20 22:15:57 -07002154 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002155 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002156 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2157 " to user switch.", i->getKey().string(),
2158 String8{clientSp->getPackageName()}.string(),
2159 i->getOwnerId(), i->getPriority().getScore(),
2160 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002161
2162 }
2163
2164 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2165 // blocking other clients from connecting in mServiceLockWrapper if held.
2166 mServiceLock.unlock();
2167
2168 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002169 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002170
2171 for (auto& i : evicted) {
2172 i->disconnect();
2173 }
2174
Jayant Chowdhary12361932018-08-27 14:46:13 -07002175 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002176
2177 // Reacquire mServiceLock
2178 mServiceLock.lock();
2179}
Ruben Brunkcc776712015-02-17 20:18:47 -08002180
Ruben Brunka8ca9152015-04-07 14:23:40 -07002181void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002182 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002183 Mutex::Autolock l(mLogLock);
2184 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002185}
2186
Ruben Brunka8ca9152015-04-07 14:23:40 -07002187void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002188 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002189 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002190 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002191 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002192}
2193
2194void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002195 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002196 // Log the clients evicted
2197 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002198 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002199}
2200
2201void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002202 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002203 // Log the client rejected
2204 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002205 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002206}
2207
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002208void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
2209 // Log torch event
2210 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
2211 torchState, clientPid));
2212}
2213
Ruben Brunk6267b532015-04-30 17:44:07 -07002214void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
2215 const std::set<userid_t>& newUserIds) {
2216 String8 newUsers = toString(newUserIds);
2217 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002218 if (oldUsers.size() == 0) {
2219 oldUsers = "<None>";
2220 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07002221 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002222 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07002223 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002224}
2225
2226void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
2227 // Log the device removal
2228 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
2229}
2230
2231void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
2232 // Log the device removal
2233 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
2234}
2235
2236void CameraService::logClientDied(int clientPid, const char* reason) {
2237 // Log the device removal
2238 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07002239}
2240
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002241void CameraService::logServiceError(const char* msg, int errorCode) {
2242 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002243 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002244}
2245
Ruben Brunk36597b22015-03-20 22:15:57 -07002246status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
2247 uint32_t flags) {
2248
Mathias Agopian65ab4712010-07-14 17:59:35 -07002249 // Permission checks
2250 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002251 case SHELL_COMMAND_TRANSACTION: {
2252 int in = data.readFileDescriptor();
2253 int out = data.readFileDescriptor();
2254 int err = data.readFileDescriptor();
2255 int argc = data.readInt32();
2256 Vector<String16> args;
2257 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
2258 args.add(data.readString16());
2259 }
2260 sp<IBinder> unusedCallback;
2261 sp<IResultReceiver> resultReceiver;
2262 status_t status;
2263 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
2264 return status;
2265 }
2266 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
2267 return status;
2268 }
2269 status = shellCommand(in, out, err, args);
2270 if (resultReceiver != nullptr) {
2271 resultReceiver->send(status);
2272 }
2273 return NO_ERROR;
2274 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002275 }
2276
2277 return BnCameraService::onTransact(code, data, reply, flags);
2278}
2279
Mathias Agopian65ab4712010-07-14 17:59:35 -07002280// We share the media players for shutter and recording sound for all clients.
2281// A reference count is kept to determine when we will actually release the
2282// media players.
2283
Jaekyun Seokef498052018-03-23 13:09:44 +09002284sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
2285 sp<MediaPlayer> mp = new MediaPlayer();
2286 status_t error;
2287 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08002288 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09002289 error = mp->prepare();
2290 }
2291 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002292 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09002293 mp->disconnect();
2294 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002295 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002296 }
2297 return mp;
2298}
2299
username5755fea2018-12-27 09:48:08 +08002300void CameraService::increaseSoundRef() {
2301 Mutex::Autolock lock(mSoundLock);
2302 mSoundRef++;
2303}
2304
2305void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002306 ATRACE_CALL();
2307
username5755fea2018-12-27 09:48:08 +08002308 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
2309 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
2310 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
2311 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
2312 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2313 }
2314 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
2315 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
2316 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
2317 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002318 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08002319 }
2320 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
2321 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
2322 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
2323 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2324 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002325 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002326}
2327
username5755fea2018-12-27 09:48:08 +08002328void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002329 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002330 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002331 if (--mSoundRef) return;
2332
2333 for (int i = 0; i < NUM_SOUNDS; i++) {
2334 if (mSoundPlayer[i] != 0) {
2335 mSoundPlayer[i]->disconnect();
2336 mSoundPlayer[i].clear();
2337 }
2338 }
2339}
2340
2341void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002342 ATRACE_CALL();
2343
Mathias Agopian65ab4712010-07-14 17:59:35 -07002344 LOG1("playSound(%d)", kind);
2345 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002346 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002347 sp<MediaPlayer> player = mSoundPlayer[kind];
2348 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08002349 player->seekTo(0);
2350 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002351 }
2352}
2353
2354// ----------------------------------------------------------------------------
2355
2356CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002357 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002358 const String16& clientPackageName,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002359 const String8& cameraIdStr,
2360 int api1CameraId, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002361 int clientPid, uid_t clientUid,
2362 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002363 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08002364 IInterface::asBinder(cameraClient),
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002365 clientPackageName,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002366 cameraIdStr, cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002367 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002368 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002369 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08002370{
Jayant Chowdhary12361932018-08-27 14:46:13 -07002371 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002372 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002373
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002374 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002375
username5755fea2018-12-27 09:48:08 +08002376 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002377
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002378 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002379}
2380
Mathias Agopian65ab4712010-07-14 17:59:35 -07002381// tear down the client
2382CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002383 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08002384 mDestructionStarted = true;
2385
username5755fea2018-12-27 09:48:08 +08002386 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002387 // unconditionally disconnect. function is idempotent
2388 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002389}
2390
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002391sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
2392
Igor Murashkin634a5152013-02-20 17:15:11 -08002393CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002394 const sp<IBinder>& remoteCallback,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002395 const String16& clientPackageName,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002396 const String8& cameraIdStr, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002397 int clientPid, uid_t clientUid,
2398 int servicePid):
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002399 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing),
2400 mClientPackageName(clientPackageName), mClientPid(clientPid), mClientUid(clientUid),
2401 mServicePid(servicePid),
2402 mDisconnected(false),
2403 mRemoteBinder(remoteCallback)
Igor Murashkin634a5152013-02-20 17:15:11 -08002404{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002405 if (sCameraService == nullptr) {
2406 sCameraService = cameraService;
2407 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002408 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08002409 mDestructionStarted = false;
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08002410
2411 // In some cases the calling code has no access to the package it runs under.
2412 // For example, NDK camera API.
2413 // In this case we will get the packages for the calling UID and pick the first one
2414 // for attributing the app op. This will work correctly for runtime permissions
2415 // as for legacy apps we will toggle the app op for all packages in the UID.
2416 // The caveat is that the operation may be attributed to the wrong package and
2417 // stats based on app ops may be slightly off.
2418 if (mClientPackageName.size() <= 0) {
2419 sp<IServiceManager> sm = defaultServiceManager();
2420 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2421 if (binder == 0) {
2422 ALOGE("Cannot get permission service");
2423 // Leave mClientPackageName unchanged (empty) and the further interaction
2424 // with camera will fail in BasicClient::startCameraOps
2425 return;
2426 }
2427
2428 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2429 Vector<String16> packages;
2430
2431 permCtrl->getPackagesForUid(mClientUid, packages);
2432
2433 if (packages.isEmpty()) {
2434 ALOGE("No packages for calling UID");
2435 // Leave mClientPackageName unchanged (empty) and the further interaction
2436 // with camera will fail in BasicClient::startCameraOps
2437 return;
2438 }
2439 mClientPackageName = packages[0];
2440 }
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002441 if (!hardware::IPCThreadState::self()->isServingCall()) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002442 mAppOpsManager = std::make_unique<AppOpsManager>();
2443 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002444}
2445
2446CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002447 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08002448 mDestructionStarted = true;
2449}
2450
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002451binder::Status CameraService::BasicClient::disconnect() {
2452 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002453 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002454 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07002455 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002456 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002457
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002458 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002459 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07002460 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
2461 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002462
2463 sp<IBinder> remote = getRemote();
2464 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002465 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08002466 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002467
2468 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07002469 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002470 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
2471 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
2472 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002473
Igor Murashkincba2c162013-03-20 15:56:31 -07002474 // client shouldn't be able to call into us anymore
2475 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002476
2477 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08002478}
2479
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002480status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2481 // No dumping of clients directly over Binder,
2482 // must go through CameraService::dump
2483 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002484 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002485 return OK;
2486}
2487
Ruben Brunkcc776712015-02-17 20:18:47 -08002488String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002489 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08002490}
2491
2492
2493int CameraService::BasicClient::getClientPid() const {
2494 return mClientPid;
2495}
2496
Ruben Brunk6267b532015-04-30 17:44:07 -07002497uid_t CameraService::BasicClient::getClientUid() const {
2498 return mClientUid;
2499}
2500
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002501bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2502 // Defaults to API2.
2503 return level == API_2;
2504}
2505
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002506status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002507 ATRACE_CALL();
2508
Igor Murashkine6800ce2013-03-04 17:25:57 -08002509 {
2510 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002511 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002512 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002513 if (mAppOpsManager != nullptr) {
2514 // Notify app ops that the camera is not available
2515 mOpsCallback = new OpsCallback(this);
2516 int32_t res;
2517 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
2518 mClientPackageName, mOpsCallback);
2519 res = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA,
2520 mClientUid, mClientPackageName, /*startIfModeDefault*/ false);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002521
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002522 if (res == AppOpsManager::MODE_ERRORED) {
2523 ALOGI("Camera %s: Access for \"%s\" has been revoked",
2524 mCameraIdStr.string(), String8(mClientPackageName).string());
2525 return PERMISSION_DENIED;
2526 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002527
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002528 if (res == AppOpsManager::MODE_IGNORED) {
2529 ALOGI("Camera %s: Access for \"%s\" has been restricted",
2530 mCameraIdStr.string(), String8(mClientPackageName).string());
2531 // Return the same error as for device policy manager rejection
2532 return -EACCES;
2533 }
Svetoslav28e8ef72015-05-11 19:21:31 -07002534 }
2535
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002536 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002537
2538 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002539 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002540
Emilian Peev573291c2018-02-10 02:10:56 +00002541 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2542 if (canCastToApiClient(API_2)) {
2543 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2544 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002545 // Transition device state to OPEN
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002546 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
Emilian Peev573291c2018-02-10 02:10:56 +00002547 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002548
Emilian Peev53722fa2019-02-22 17:47:20 -08002549 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
2550
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002551 return OK;
2552}
2553
2554status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002555 ATRACE_CALL();
2556
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002557 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002558 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002559 // Notify app ops that the camera is available again
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002560 if (mAppOpsManager != nullptr) {
2561 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
2562 mClientPackageName);
2563 mOpsActive = false;
2564 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002565 // This function is called when a client disconnects. This should
2566 // release the camera, but actually only if it was in a proper
2567 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002568 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002569 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002570
Ruben Brunkcc776712015-02-17 20:18:47 -08002571 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002572 sCameraService->updateStatus(StatusInternal::PRESENT,
2573 mCameraIdStr, rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002574
Emilian Peev573291c2018-02-10 02:10:56 +00002575 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2576 if (canCastToApiClient(API_2)) {
2577 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2578 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002579 // Transition device state to CLOSED
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002580 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
Emilian Peev573291c2018-02-10 02:10:56 +00002581 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002582 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002583 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002584 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
2585 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002586 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002587 mOpsCallback.clear();
2588
Emilian Peev53722fa2019-02-22 17:47:20 -08002589 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
2590
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002591 return OK;
2592}
2593
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002594void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002595 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002596 if (mAppOpsManager == nullptr) {
2597 return;
2598 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002599 if (op != AppOpsManager::OP_CAMERA) {
2600 ALOGW("Unexpected app ops notification received: %d", op);
2601 return;
2602 }
2603
2604 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002605 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002606 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002607 ALOGV("checkOp returns: %d, %s ", res,
2608 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
2609 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
2610 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
2611 "UNKNOWN");
2612
2613 if (res != AppOpsManager::MODE_ALLOWED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002614 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002615 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08002616 block();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002617 }
2618}
2619
Svet Ganova453d0d2018-01-11 15:37:58 -08002620void CameraService::BasicClient::block() {
2621 ATRACE_CALL();
2622
2623 // Reset the client PID to allow server-initiated disconnect,
2624 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07002625 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08002626 CaptureResultExtras resultExtras; // a dummy result (invalid)
2627 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
2628 disconnect();
2629}
2630
Mathias Agopian65ab4712010-07-14 17:59:35 -07002631// ----------------------------------------------------------------------------
2632
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002633void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07002634 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002635 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07002636 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07002637 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
2638 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
2639 api1ErrorCode = CAMERA_ERROR_DISABLED;
2640 }
2641 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07002642 } else {
2643 ALOGE("mRemoteCallback is NULL!!");
2644 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002645}
2646
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002647// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002648binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002649 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002650 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08002651}
2652
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002653bool CameraService::Client::canCastToApiClient(apiLevel level) const {
2654 return level == API_1;
2655}
2656
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002657CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
2658 mClient(client) {
2659}
2660
2661void CameraService::Client::OpsCallback::opChanged(int32_t op,
2662 const String16& packageName) {
2663 sp<BasicClient> client = mClient.promote();
2664 if (client != NULL) {
2665 client->opChanged(op, packageName);
2666 }
2667}
2668
Mathias Agopian65ab4712010-07-14 17:59:35 -07002669// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08002670// UidPolicy
2671// ----------------------------------------------------------------------------
2672
2673void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002674 Mutex::Autolock _l(mUidLock);
2675
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002676 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07002677 status_t res = mAm.linkToDeath(this);
2678 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08002679 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08002680 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08002681 ActivityManager::PROCESS_STATE_UNKNOWN,
2682 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002683 if (res == OK) {
2684 mRegistered = true;
2685 ALOGV("UidPolicy: Registered with ActivityManager");
2686 }
Svet Ganova453d0d2018-01-11 15:37:58 -08002687}
2688
2689void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002690 Mutex::Autolock _l(mUidLock);
2691
Steven Moreland2f348142019-07-02 15:59:07 -07002692 mAm.unregisterUidObserver(this);
2693 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002694 mRegistered = false;
2695 mActiveUids.clear();
2696 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08002697}
2698
2699void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
2700 onUidIdle(uid, disabled);
2701}
2702
2703void CameraService::UidPolicy::onUidActive(uid_t uid) {
2704 Mutex::Autolock _l(mUidLock);
2705 mActiveUids.insert(uid);
2706}
2707
2708void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
2709 bool deleted = false;
2710 {
2711 Mutex::Autolock _l(mUidLock);
2712 if (mActiveUids.erase(uid) > 0) {
2713 deleted = true;
2714 }
2715 }
2716 if (deleted) {
2717 sp<CameraService> service = mService.promote();
2718 if (service != nullptr) {
2719 service->blockClientsForUid(uid);
2720 }
2721 }
2722}
2723
Emilian Peev53722fa2019-02-22 17:47:20 -08002724void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
2725 int64_t /*procStateSeq*/) {
2726 bool procStateChange = false;
2727 {
2728 Mutex::Autolock _l(mUidLock);
2729 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
2730 (mMonitoredUids[uid].first != procState)) {
2731 mMonitoredUids[uid].first = procState;
2732 procStateChange = true;
2733 }
2734 }
2735
2736 if (procStateChange) {
2737 sp<CameraService> service = mService.promote();
2738 if (service != nullptr) {
2739 service->notifyMonitoredUids();
2740 }
2741 }
2742}
2743
2744void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
2745 Mutex::Autolock _l(mUidLock);
2746 auto it = mMonitoredUids.find(uid);
2747 if (it != mMonitoredUids.end()) {
2748 it->second.second++;
2749 } else {
2750 mMonitoredUids.emplace(
2751 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
2752 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
2753 }
2754}
2755
2756void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
2757 Mutex::Autolock _l(mUidLock);
2758 auto it = mMonitoredUids.find(uid);
2759 if (it != mMonitoredUids.end()) {
2760 it->second.second--;
2761 if (it->second.second == 0) {
2762 mMonitoredUids.erase(it);
2763 }
2764 } else {
2765 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
2766 }
2767}
2768
Svet Ganov7b4ab782018-03-25 12:48:10 -07002769bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002770 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07002771 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08002772}
2773
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07002774static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
2775static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07002776
Svet Ganov7b4ab782018-03-25 12:48:10 -07002777bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002778 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002779 // If activity manager is unreachable, assume everything is active
2780 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002781 return true;
2782 }
2783 auto it = mOverrideUids.find(uid);
2784 if (it != mOverrideUids.end()) {
2785 return it->second;
2786 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07002787 bool active = mActiveUids.find(uid) != mActiveUids.end();
2788 if (!active) {
2789 // We want active UIDs to always access camera with their first attempt since
2790 // there is no guarantee the app is robustly written and would retry getting
2791 // the camera on failure. The inverse case is not a problem as we would take
2792 // camera away soon once we get the callback that the uid is no longer active.
2793 ActivityManager am;
2794 // Okay to access with a lock held as UID changes are dispatched without
2795 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07002796 int64_t startTimeMillis = 0;
2797 do {
2798 // TODO: Fix this b/109950150!
2799 // Okay this is a hack. There is a race between the UID turning active and
2800 // activity being resumed. The proper fix is very risky, so we temporary add
2801 // some polling which should happen pretty rarely anyway as the race is hard
2802 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07002803 active = mActiveUids.find(uid) != mActiveUids.end();
2804 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07002805 if (active) {
2806 break;
2807 }
2808 if (startTimeMillis <= 0) {
2809 startTimeMillis = uptimeMillis();
2810 }
2811 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07002812 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07002813 if (remainingTimeMillis <= 0) {
2814 break;
2815 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07002816 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
2817
2818 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07002819 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07002820 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07002821 } while (true);
2822
Svet Ganov7b4ab782018-03-25 12:48:10 -07002823 if (active) {
2824 // Now that we found out the UID is actually active, cache that
2825 mActiveUids.insert(uid);
2826 }
2827 }
2828 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08002829}
2830
Varun Shahb42f1eb2019-04-16 14:45:13 -07002831int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
2832 Mutex::Autolock _l(mUidLock);
2833 return getProcStateLocked(uid);
2834}
2835
2836int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
2837 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
2838 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
2839 procState = mMonitoredUids[uid].first;
2840 }
2841 return procState;
2842}
2843
Svet Ganov7b4ab782018-03-25 12:48:10 -07002844void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
2845 String16 callingPackage, bool active) {
2846 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08002847}
2848
Svet Ganov7b4ab782018-03-25 12:48:10 -07002849void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
2850 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08002851}
2852
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002853void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
2854 Mutex::Autolock _l(mUidLock);
2855 ALOGV("UidPolicy: ActivityManager has died");
2856 mRegistered = false;
2857 mActiveUids.clear();
2858}
2859
Svet Ganov7b4ab782018-03-25 12:48:10 -07002860void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
2861 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002862 bool wasActive = false;
2863 bool isActive = false;
2864 {
2865 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07002866 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08002867 mOverrideUids.erase(uid);
2868 if (insert) {
2869 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
2870 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07002871 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08002872 }
2873 if (wasActive != isActive && !isActive) {
2874 sp<CameraService> service = mService.promote();
2875 if (service != nullptr) {
2876 service->blockClientsForUid(uid);
2877 }
2878 }
2879}
2880
2881// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08002882// SensorPrivacyPolicy
2883// ----------------------------------------------------------------------------
2884void CameraService::SensorPrivacyPolicy::registerSelf() {
2885 Mutex::Autolock _l(mSensorPrivacyLock);
2886 if (mRegistered) {
2887 return;
2888 }
2889 SensorPrivacyManager spm;
2890 spm.addSensorPrivacyListener(this);
2891 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
2892 status_t res = spm.linkToDeath(this);
2893 if (res == OK) {
2894 mRegistered = true;
2895 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
2896 }
2897}
2898
2899void CameraService::SensorPrivacyPolicy::unregisterSelf() {
2900 Mutex::Autolock _l(mSensorPrivacyLock);
2901 SensorPrivacyManager spm;
2902 spm.removeSensorPrivacyListener(this);
2903 spm.unlinkToDeath(this);
2904 mRegistered = false;
2905 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
2906}
2907
2908bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
2909 Mutex::Autolock _l(mSensorPrivacyLock);
2910 return mSensorPrivacyEnabled;
2911}
2912
2913binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
2914 {
2915 Mutex::Autolock _l(mSensorPrivacyLock);
2916 mSensorPrivacyEnabled = enabled;
2917 }
2918 // if sensor privacy is enabled then block all clients from accessing the camera
2919 if (enabled) {
2920 sp<CameraService> service = mService.promote();
2921 if (service != nullptr) {
2922 service->blockAllClients();
2923 }
2924 }
2925 return binder::Status::ok();
2926}
2927
2928void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
2929 Mutex::Autolock _l(mSensorPrivacyLock);
2930 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
2931 mRegistered = false;
2932}
2933
2934// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08002935// CameraState
2936// ----------------------------------------------------------------------------
2937
2938CameraService::CameraState::CameraState(const String8& id, int cost,
2939 const std::set<String8>& conflicting) : mId(id),
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002940 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08002941
2942CameraService::CameraState::~CameraState() {}
2943
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002944CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08002945 Mutex::Autolock lock(mStatusLock);
2946 return mStatus;
2947}
2948
2949CameraParameters CameraService::CameraState::getShimParams() const {
2950 return mShimParams;
2951}
2952
2953void CameraService::CameraState::setShimParams(const CameraParameters& params) {
2954 mShimParams = params;
2955}
2956
2957int CameraService::CameraState::getCost() const {
2958 return mCost;
2959}
2960
2961std::set<String8> CameraService::CameraState::getConflicting() const {
2962 return mConflicting;
2963}
2964
2965String8 CameraService::CameraState::getId() const {
2966 return mId;
2967}
2968
2969// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07002970// ClientEventListener
2971// ----------------------------------------------------------------------------
2972
2973void CameraService::ClientEventListener::onClientAdded(
2974 const resource_policy::ClientDescriptor<String8,
2975 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07002976 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07002977 if (basicClient.get() != nullptr) {
2978 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2979 notifier.noteStartCamera(descriptor.getKey(),
2980 static_cast<int>(basicClient->getClientUid()));
2981 }
2982}
2983
2984void CameraService::ClientEventListener::onClientRemoved(
2985 const resource_policy::ClientDescriptor<String8,
2986 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07002987 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07002988 if (basicClient.get() != nullptr) {
2989 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2990 notifier.noteStopCamera(descriptor.getKey(),
2991 static_cast<int>(basicClient->getClientUid()));
2992 }
2993}
2994
2995
2996// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08002997// CameraClientManager
2998// ----------------------------------------------------------------------------
2999
Ruben Brunk99e69712015-05-26 17:25:07 -07003000CameraService::CameraClientManager::CameraClientManager() {
3001 setListener(std::make_shared<ClientEventListener>());
3002}
3003
Ruben Brunkcc776712015-02-17 20:18:47 -08003004CameraService::CameraClientManager::~CameraClientManager() {}
3005
3006sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
3007 const String8& id) const {
3008 auto descriptor = get(id);
3009 if (descriptor == nullptr) {
3010 return sp<BasicClient>{nullptr};
3011 }
3012 return descriptor->getValue();
3013}
3014
3015String8 CameraService::CameraClientManager::toString() const {
3016 auto all = getAll();
3017 String8 ret("[");
3018 bool hasAny = false;
3019 for (auto& i : all) {
3020 hasAny = true;
3021 String8 key = i->getKey();
3022 int32_t cost = i->getCost();
3023 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00003024 int32_t score = i->getPriority().getScore();
3025 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08003026 auto conflicting = i->getConflicting();
3027 auto clientSp = i->getValue();
3028 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07003029 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08003030 if (clientSp.get() != nullptr) {
3031 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07003032 uid_t clientUid = clientSp->getClientUid();
3033 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003034 }
Emilian Peev8131a262017-02-01 12:33:43 +00003035 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
3036 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08003037
Ruben Brunk6267b532015-04-30 17:44:07 -07003038 if (clientSp.get() != nullptr) {
3039 ret.appendFormat("User Id: %d, ", clientUserId);
3040 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003041 if (packageName.size() != 0) {
3042 ret.appendFormat("Client Package Name: %s", packageName.string());
3043 }
3044
3045 ret.append(", Conflicting Client Devices: {");
3046 for (auto& j : conflicting) {
3047 ret.appendFormat("%s, ", j.string());
3048 }
3049 ret.append("})");
3050 }
3051 if (hasAny) ret.append("\n");
3052 ret.append("]\n");
3053 return ret;
3054}
3055
3056CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3057 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00003058 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
3059 int32_t state) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003060
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003061 bool isVendorClient = hardware::IPCThreadState::self()->isServingCall();
3062 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
3063 int32_t state_adj = isVendorClient ? kVendorClientState: state;
3064
Ruben Brunkcc776712015-02-17 20:18:47 -08003065 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003066 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08003067}
3068
3069CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3070 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
3071 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00003072 partial->getConflicting(), partial->getPriority().getScore(),
3073 partial->getOwnerId(), partial->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08003074}
3075
3076// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07003077
3078static const int kDumpLockRetries = 50;
3079static const int kDumpLockSleep = 60000;
3080
3081static bool tryLock(Mutex& mutex)
3082{
3083 bool locked = false;
3084 for (int i = 0; i < kDumpLockRetries; ++i) {
3085 if (mutex.tryLock() == NO_ERROR) {
3086 locked = true;
3087 break;
3088 }
3089 usleep(kDumpLockSleep);
3090 }
3091 return locked;
3092}
3093
3094status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003095 ATRACE_CALL();
3096
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003097 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003098 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003099 CameraThreadState::getCallingPid(),
3100 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003101 return NO_ERROR;
3102 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003103 bool locked = tryLock(mServiceLock);
3104 // failed to lock - CameraService is probably deadlocked
3105 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003106 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003107 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003108
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003109 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003110 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07003111
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003112 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003113 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08003114
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003115 if (locked) mServiceLock.unlock();
3116 return NO_ERROR;
3117 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003118 dprintf(fd, "\n== Service global info: ==\n\n");
3119 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003120 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
3121 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
3122 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
3123 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003124 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003125 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
3126 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003127
3128 dumpEventLog(fd);
3129
3130 bool stateLocked = tryLock(mCameraStatesLock);
3131 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003132 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003133 }
3134
Emilian Peevbd8c5032018-02-14 23:05:40 +00003135 int argSize = args.size();
3136 for (int i = 0; i < argSize; i++) {
3137 if (args[i] == TagMonitor::kMonitorOption) {
3138 if (i + 1 < argSize) {
3139 mMonitorTags = String8(args[i + 1]);
3140 }
3141 break;
3142 }
3143 }
3144
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003145 for (auto& state : mCameraStates) {
3146 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003147
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003148 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003149
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003150 CameraParameters p = state.second->getShimParams();
3151 if (!p.isEmpty()) {
3152 dprintf(fd, " Camera1 API shim is using parameters:\n ");
3153 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003154 }
3155
3156 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08003157 if (clientDescriptor != nullptr) {
3158 dprintf(fd, " Device %s is open. Client instance dump:\n",
3159 cameraId.string());
3160 dprintf(fd, " Client priority score: %d state: %d\n",
3161 clientDescriptor->getPriority().getScore(),
3162 clientDescriptor->getPriority().getState());
3163 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
3164
3165 auto client = clientDescriptor->getValue();
3166 dprintf(fd, " Client package: %s\n",
3167 String8(client->getPackageName()).string());
3168
3169 client->dumpClient(fd, args);
3170 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003171 dprintf(fd, " Device %s is closed, no client instance\n",
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003172 cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003173 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003174
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003175 }
3176
3177 if (stateLocked) mCameraStatesLock.unlock();
3178
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003179 if (locked) mServiceLock.unlock();
3180
Emilian Peevf53f66e2017-04-11 14:29:43 +01003181 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003182
3183 dprintf(fd, "\n== Vendor tags: ==\n\n");
3184
3185 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
3186 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00003187 sp<VendorTagDescriptorCache> cache =
3188 VendorTagDescriptorCache::getGlobalVendorTagCache();
3189 if (cache == NULL) {
3190 dprintf(fd, "No vendor tags.\n");
3191 } else {
3192 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
3193 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003194 } else {
3195 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
3196 }
3197
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003198 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003199 dprintf(fd, "\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003200 camera3::CameraTraces::dump(fd, args);
3201
3202 // Process dump arguments, if any
3203 int n = args.size();
3204 String16 verboseOption("-v");
3205 String16 unreachableOption("--unreachable");
3206 for (int i = 0; i < n; i++) {
3207 if (args[i] == verboseOption) {
3208 // change logging level
3209 if (i + 1 >= n) continue;
3210 String8 levelStr(args[i+1]);
3211 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003212 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003213 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003214 } else if (args[i] == unreachableOption) {
3215 // Dump memory analysis
3216 // TODO - should limit be an argument parameter?
3217 UnreachableMemoryInfo info;
3218 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
3219 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003220 dprintf(fd, "\n== Unable to dump unreachable memory. "
3221 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003222 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003223 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003224 std::string s = info.ToString(/*log_contents*/ true);
3225 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003226 }
3227 }
3228 }
3229 return NO_ERROR;
3230}
3231
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003232void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003233 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003234
3235 Mutex::Autolock l(mLogLock);
3236 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003237 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003238 }
3239
3240 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003241 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003242 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003243 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003244 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003245 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003246}
3247
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003248void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003249 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003250 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
3251 if (mTorchClientMap[i] == who) {
3252 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003253 String8 cameraId = mTorchClientMap.keyAt(i);
3254 status_t res = mFlashlight->setTorchMode(cameraId, false);
3255 if (res) {
3256 ALOGE("%s: torch client died but couldn't turn off torch: "
3257 "%s (%d)", __FUNCTION__, strerror(-res), res);
3258 return;
3259 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003260 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003261 break;
3262 }
3263 }
3264}
3265
Ruben Brunkcc776712015-02-17 20:18:47 -08003266/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003267
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003268 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07003269 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
3270 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003271 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003272 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003273 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003274
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003275 // check torch client
3276 handleTorchClientBinderDied(who);
3277
3278 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08003279 if(!evictClientIdByRemote(who)) {
3280 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003281 return;
3282 }
3283
Ruben Brunkcc776712015-02-17 20:18:47 -08003284 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
3285 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003286}
3287
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003288void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003289 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08003290}
3291
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003292void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
3293 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003294 // Do not lock mServiceLock here or can get into a deadlock from
3295 // connect() -> disconnect -> updateStatus
3296
3297 auto state = getCameraState(cameraId);
3298
3299 if (state == nullptr) {
3300 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
3301 cameraId.string());
3302 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07003303 }
3304
Ruben Brunkcc776712015-02-17 20:18:47 -08003305 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
3306 // of the listeners with both the mStatusStatus and mStatusListenerLock held
3307 state->updateStatus(status, cameraId, rejectSourceStates, [this]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003308 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003309
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003310 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003311 // Update torch status if it has a flash unit.
3312 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003313 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003314 if (getTorchStatusLocked(cameraId, &torchStatus) !=
3315 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003316 TorchModeStatus newTorchStatus =
3317 status == StatusInternal::PRESENT ?
3318 TorchModeStatus::AVAILABLE_OFF :
3319 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003320 if (torchStatus != newTorchStatus) {
3321 onTorchStatusChangedLocked(cameraId, newTorchStatus);
3322 }
3323 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003324 }
3325
3326 Mutex::Autolock lock(mStatusListenerLock);
3327
3328 for (auto& listener : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003329 if (shouldSkipStatusUpdates(cameraId, listener->isVendorListener(),
3330 listener->getListenerPid(), listener->getListenerUid())) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003331 ALOGV("Skipping camera discovery callback for system-only camera %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003332 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003333 continue;
3334 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003335 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08003336 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08003337 }
3338 });
Igor Murashkincba2c162013-03-20 15:56:31 -07003339}
3340
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003341template<class Func>
3342void CameraService::CameraState::updateStatus(StatusInternal status,
3343 const String8& cameraId,
3344 std::initializer_list<StatusInternal> rejectSourceStates,
3345 Func onStatusUpdatedLocked) {
3346 Mutex::Autolock lock(mStatusLock);
3347 StatusInternal oldStatus = mStatus;
3348 mStatus = status;
3349
3350 if (oldStatus == status) {
3351 return;
3352 }
3353
3354 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
3355 cameraId.string(), oldStatus, status);
3356
3357 if (oldStatus == StatusInternal::NOT_PRESENT &&
3358 (status != StatusInternal::PRESENT &&
3359 status != StatusInternal::ENUMERATING)) {
3360
3361 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
3362 __FUNCTION__);
3363 mStatus = oldStatus;
3364 return;
3365 }
3366
3367 /**
3368 * Sometimes we want to conditionally do a transition.
3369 * For example if a client disconnects, we want to go to PRESENT
3370 * only if we weren't already in NOT_PRESENT or ENUMERATING.
3371 */
3372 for (auto& rejectStatus : rejectSourceStates) {
3373 if (oldStatus == rejectStatus) {
3374 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
3375 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
3376 mStatus = oldStatus;
3377 return;
3378 }
3379 }
3380
3381 onStatusUpdatedLocked(cameraId, status);
3382}
3383
Eino-Ville Talvalae8c96c72017-06-27 12:24:07 -07003384void CameraService::updateProxyDeviceState(int newState,
Emilian Peev573291c2018-02-10 02:10:56 +00003385 const String8& cameraId, int facing, const String16& clientName, int apiLevel) {
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003386 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
3387 if (proxyBinder == nullptr) return;
3388 String16 id(cameraId);
Emilian Peev573291c2018-02-10 02:10:56 +00003389 proxyBinder->notifyCameraState(id, newState, facing, clientName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003390}
3391
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003392status_t CameraService::getTorchStatusLocked(
3393 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003394 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003395 if (!status) {
3396 return BAD_VALUE;
3397 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003398 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3399 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003400 // invalid camera ID or the camera doesn't have a flash unit
3401 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003402 }
3403
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003404 *status = mTorchStatusMap.valueAt(index);
3405 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003406}
3407
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003408status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003409 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003410 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3411 if (index == NAME_NOT_FOUND) {
3412 return BAD_VALUE;
3413 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003414 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003415
3416 return OK;
3417}
3418
Svet Ganova453d0d2018-01-11 15:37:58 -08003419void CameraService::blockClientsForUid(uid_t uid) {
3420 const auto clients = mActiveClientManager.getAll();
3421 for (auto& current : clients) {
3422 if (current != nullptr) {
3423 const auto basicClient = current->getValue();
3424 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
3425 basicClient->block();
3426 }
3427 }
3428 }
3429}
3430
Michael Grooverd1d435a2018-12-18 17:39:42 -08003431void CameraService::blockAllClients() {
3432 const auto clients = mActiveClientManager.getAll();
3433 for (auto& current : clients) {
3434 if (current != nullptr) {
3435 const auto basicClient = current->getValue();
3436 if (basicClient.get() != nullptr) {
3437 basicClient->block();
3438 }
3439 }
3440 }
3441}
3442
Svet Ganova453d0d2018-01-11 15:37:58 -08003443// NOTE: This is a remote API - make sure all args are validated
3444status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
3445 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
3446 return PERMISSION_DENIED;
3447 }
3448 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
3449 return BAD_VALUE;
3450 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003451 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003452 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003453 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003454 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003455 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003456 return handleGetUidState(args, out, err);
3457 } else if (args.size() == 1 && args[0] == String16("help")) {
3458 printHelp(out);
3459 return NO_ERROR;
3460 }
3461 printHelp(err);
3462 return BAD_VALUE;
3463}
3464
3465status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003466 String16 packageName = args[1];
3467
Svet Ganova453d0d2018-01-11 15:37:58 -08003468 bool active = false;
3469 if (args[2] == String16("active")) {
3470 active = true;
3471 } else if ((args[2] != String16("idle"))) {
3472 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
3473 return BAD_VALUE;
3474 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003475
3476 int userId = 0;
3477 if (args.size() >= 5 && args[3] == String16("--user")) {
3478 userId = atoi(String8(args[4]));
3479 }
3480
3481 uid_t uid;
3482 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
3483 return BAD_VALUE;
3484 }
3485
3486 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08003487 return NO_ERROR;
3488}
3489
3490status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003491 String16 packageName = args[1];
3492
3493 int userId = 0;
3494 if (args.size() >= 4 && args[2] == String16("--user")) {
3495 userId = atoi(String8(args[3]));
3496 }
3497
3498 uid_t uid;
3499 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003500 return BAD_VALUE;
3501 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003502
3503 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08003504 return NO_ERROR;
3505}
3506
3507status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003508 String16 packageName = args[1];
3509
3510 int userId = 0;
3511 if (args.size() >= 4 && args[2] == String16("--user")) {
3512 userId = atoi(String8(args[3]));
3513 }
3514
3515 uid_t uid;
3516 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003517 return BAD_VALUE;
3518 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003519
3520 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003521 return dprintf(out, "active\n");
3522 } else {
3523 return dprintf(out, "idle\n");
3524 }
3525}
3526
3527status_t CameraService::printHelp(int out) {
3528 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07003529 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
3530 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
3531 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08003532 " help print this message\n");
3533}
3534
Mathias Agopian65ab4712010-07-14 17:59:35 -07003535}; // namespace android