blob: c456b1f4b5becd76c7466f4555e3fb54fa362ca6 [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>
Svet Ganova453d0d2018-01-11 15:37:58 -080036#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080037#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070038#include <binder/IPCThreadState.h>
39#include <binder/IServiceManager.h>
40#include <binder/MemoryBase.h>
41#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080042#include <binder/PermissionController.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080043#include <binder/ProcessInfoService.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080044#include <binder/IResultReceiver.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070046#include <cutils/properties.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080047#include <cutils/misc.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080048#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070049#include <hardware/hardware.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070050#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070051#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080052#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070053#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070054#include <mediautils/BatteryNotifier.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070055#include <utils/Errors.h>
56#include <utils/Log.h>
57#include <utils/String16.h>
Svet Ganovbd39b492018-06-08 15:03:46 -070058#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080059#include <utils/Trace.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080060#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080061#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070062#include <system/camera_metadata.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080063
Ruben Brunkb2119af2014-05-09 19:57:56 -070064#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070065
66#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070067#include "api1/CameraClient.h"
68#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070069#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070070#include "utils/CameraTraces.h"
Emilian Peevbd8c5032018-02-14 23:05:40 +000071#include "utils/TagMonitor.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070072
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080073namespace {
74 const char* kPermissionServiceName = "permission";
75}; // namespace anonymous
76
Mathias Agopian65ab4712010-07-14 17:59:35 -070077namespace android {
78
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080079using binder::Status;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -080080using hardware::ICamera;
81using hardware::ICameraClient;
Eino-Ville Talvalae8c96c72017-06-27 12:24:07 -070082using hardware::ICameraServiceProxy;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -080083using hardware::ICameraServiceListener;
84using hardware::camera::common::V1_0::CameraDeviceStatus;
85using hardware::camera::common::V1_0::TorchModeStatus;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080086
Mathias Agopian65ab4712010-07-14 17:59:35 -070087// ----------------------------------------------------------------------------
88// Logging support -- this is for debugging only
89// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -070090volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -070091
Steve Blockb8a80522011-12-20 16:23:08 +000092#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
93#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -070094
95static void setLogLevel(int level) {
96 android_atomic_write(level, &gLogLevel);
97}
98
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080099// Convenience methods for constructing binder::Status objects for error returns
100
101#define STATUS_ERROR(errorCode, errorString) \
102 binder::Status::fromServiceSpecificError(errorCode, \
103 String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
104
105#define STATUS_ERROR_FMT(errorCode, errorString, ...) \
106 binder::Status::fromServiceSpecificError(errorCode, \
107 String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, \
108 __VA_ARGS__))
109
Mathias Agopian65ab4712010-07-14 17:59:35 -0700110// ----------------------------------------------------------------------------
111
Svet Ganova453d0d2018-01-11 15:37:58 -0800112static const String16 sManageCameraPermission("android.permission.MANAGE_CAMERA");
113
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800114CameraService::CameraService() :
115 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800116 mNumberOfCameras(0),
Emilian Peevf53f66e2017-04-11 14:29:43 +0100117 mSoundRef(0), mInitialized(false) {
Steve Blockdf64d152012-01-04 20:05:49 +0000118 ALOGI("CameraService started (pid=%d)", getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800119 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700120}
121
Iliyan Malchev8951a972011-04-14 16:55:59 -0700122void CameraService::onFirstRef()
123{
Ruben Brunkcc776712015-02-17 20:18:47 -0800124 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800125
Iliyan Malchev8951a972011-04-14 16:55:59 -0700126 BnCameraService::onFirstRef();
127
Ruben Brunk99e69712015-05-26 17:25:07 -0700128 // Update battery life tracking if service is restarting
129 BatteryNotifier& notifier(BatteryNotifier::getInstance());
130 notifier.noteResetCamera();
131 notifier.noteResetFlashlight();
132
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800133 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800134
Emilian Peevf53f66e2017-04-11 14:29:43 +0100135 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800136 if (res == OK) {
137 mInitialized = true;
138 }
139
140 CameraService::pingCameraServiceProxy();
Svet Ganova453d0d2018-01-11 15:37:58 -0800141
142 mUidPolicy = new UidPolicy(this);
143 mUidPolicy->registerSelf();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800144}
145
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800146status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800147 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100148
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800149 std::vector<std::string> deviceIds;
150 {
151 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800152
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800153 if (nullptr == mCameraProviderManager.get()) {
154 mCameraProviderManager = new CameraProviderManager();
155 res = mCameraProviderManager->initialize(this);
156 if (res != OK) {
157 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
158 __FUNCTION__, strerror(-res), res);
159 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100160 }
161 }
162
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800163
164 // Setup vendor tags before we call get_camera_info the first time
165 // because HAL might need to setup static vendor keys in get_camera_info
166 // TODO: maybe put this into CameraProviderManager::initialize()?
167 mCameraProviderManager->setUpVendorTags();
168
169 if (nullptr == mFlashlight.get()) {
170 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700171 }
172
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800173 res = mFlashlight->findFlashUnits();
174 if (res != OK) {
175 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
176 }
177
178 deviceIds = mCameraProviderManager->getCameraDeviceIds();
179 }
180
181
182 for (auto& cameraId : deviceIds) {
183 String8 id8 = String8(cameraId.c_str());
Shuzhen Wange1aedc52018-11-20 10:04:08 -0800184 if (getCameraState(id8) == nullptr) {
185 onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
186 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800187 }
188
189 return OK;
190}
191
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700192sp<ICameraServiceProxy> CameraService::getCameraServiceProxy() {
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800193 sp<ICameraServiceProxy> proxyBinder = nullptr;
194#ifndef __BRILLO__
Ruben Brunk2823ce02015-05-19 17:25:13 -0700195 sp<IServiceManager> sm = defaultServiceManager();
Eino-Ville Talvalaf4db13d2016-12-08 11:20:51 -0800196 // Use checkService because cameraserver normally starts before the
197 // system server and the proxy service. So the long timeout that getService
198 // has before giving up is inappropriate.
199 sp<IBinder> binder = sm->checkService(String16("media.camera.proxy"));
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800200 if (binder != nullptr) {
201 proxyBinder = interface_cast<ICameraServiceProxy>(binder);
Ruben Brunk2823ce02015-05-19 17:25:13 -0700202 }
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800203#endif
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700204 return proxyBinder;
205}
206
207void CameraService::pingCameraServiceProxy() {
208 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
209 if (proxyBinder == nullptr) return;
Ruben Brunk2823ce02015-05-19 17:25:13 -0700210 proxyBinder->pingForUserUpdate();
Iliyan Malchev8951a972011-04-14 16:55:59 -0700211}
212
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800213void CameraService::broadcastTorchModeStatus(const String8& cameraId, TorchModeStatus status) {
214 Mutex::Autolock lock(mStatusListenerLock);
215
216 for (auto& i : mListenerList) {
217 i->onTorchStatusChanged(mapToInterface(status), String16{cameraId});
218 }
219}
220
Mathias Agopian65ab4712010-07-14 17:59:35 -0700221CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800222 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800223 mUidPolicy->unregisterSelf();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700224}
225
Emilian Peevaee727d2017-05-04 16:35:48 +0100226void CameraService::onNewProviderRegistered() {
227 enumerateProviders();
228}
229
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800230void CameraService::updateCameraNumAndIds() {
231 Mutex::Autolock l(mServiceLock);
232 mNumberOfCameras = mCameraProviderManager->getCameraCount();
233 mNormalDeviceIds =
234 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
235}
236
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100237void CameraService::addStates(const String8 id) {
238 std::string cameraId(id.c_str());
239 hardware::camera::common::V1_0::CameraResourceCost cost;
240 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
241 if (res != OK) {
242 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
243 return;
244 }
245 std::set<String8> conflicting;
246 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
247 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
248 }
249
250 {
251 Mutex::Autolock lock(mCameraStatesLock);
252 mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
253 conflicting));
254 }
255
256 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100257 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100258 mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800259
260 broadcastTorchModeStatus(id, TorchModeStatus::AVAILABLE_OFF);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100261 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800262
263 updateCameraNumAndIds();
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100264 logDeviceAdded(id, "Device added");
265}
266
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100267void CameraService::removeStates(const String8 id) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800268 updateCameraNumAndIds();
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100269 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100270 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100271 mTorchStatusMap.removeItem(id);
272 }
273
274 {
275 Mutex::Autolock lock(mCameraStatesLock);
276 mCameraStates.erase(id);
277 }
278}
279
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800280void CameraService::onDeviceStatusChanged(const String8& id,
281 CameraDeviceStatus newHalStatus) {
282 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
283 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700284
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800285 StatusInternal newStatus = mapToInternal(newHalStatus);
286
Ruben Brunkcc776712015-02-17 20:18:47 -0800287 std::shared_ptr<CameraState> state = getCameraState(id);
288
289 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700290 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100291 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700292 __FUNCTION__, id.string());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100293
294 // First add as absent to make sure clients are notified below
295 addStates(id);
296
297 updateStatus(newStatus, id);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700298 } else {
299 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
300 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700301 return;
302 }
303
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800304 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800305
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800306 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800307 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700308 return;
309 }
310
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800311 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700312 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
313 newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800314
315 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
316 // to this device until the status changes
317 updateStatus(StatusInternal::NOT_PRESENT, id);
318
Ruben Brunkcc776712015-02-17 20:18:47 -0800319 sp<BasicClient> clientToDisconnect;
Igor Murashkincba2c162013-03-20 15:56:31 -0700320 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800321 // Don't do this in updateStatus to avoid deadlock over mServiceLock
322 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700323
Ruben Brunkcc776712015-02-17 20:18:47 -0800324 // Remove cached shim parameters
325 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700326
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700327 // Remove the client from the list of active clients, if there is one
Ruben Brunkcc776712015-02-17 20:18:47 -0800328 clientToDisconnect = removeClientLocked(id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700329 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800330
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700331 // Disconnect client
332 if (clientToDisconnect.get() != nullptr) {
333 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
334 __FUNCTION__, id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800335 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800336 clientToDisconnect->notifyError(
337 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -0800338 CaptureResultExtras{});
Ruben Brunkcc776712015-02-17 20:18:47 -0800339 // Ensure not in binder RPC so client disconnect PID checks work correctly
340 LOG_ALWAYS_FATAL_IF(getCallingPid() != getpid(),
341 "onDeviceStatusChanged must be called from the camera service process!");
342 clientToDisconnect->disconnect();
Igor Murashkincba2c162013-03-20 15:56:31 -0700343 }
344
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100345 removeStates(id);
Ruben Brunkcc776712015-02-17 20:18:47 -0800346 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800347 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700348 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
349 newStatus));
350 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800351 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700352 }
353
Igor Murashkincba2c162013-03-20 15:56:31 -0700354}
355
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800356void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800357 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800358 Mutex::Autolock al(mTorchStatusMutex);
359 onTorchStatusChangedLocked(cameraId, newStatus);
360}
361
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800362void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800363 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800364 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
365 __FUNCTION__, cameraId.string(), newStatus);
366
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800367 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800368 status_t res = getTorchStatusLocked(cameraId, &status);
369 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700370 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
371 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800372 return;
373 }
374 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800375 return;
376 }
377
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800378 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800379 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800380 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
381 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800382 return;
383 }
384
Ruben Brunkcc776712015-02-17 20:18:47 -0800385 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700386 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700387 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700388 auto iter = mTorchUidMap.find(cameraId);
389 if (iter != mTorchUidMap.end()) {
390 int oldUid = iter->second.second;
391 int newUid = iter->second.first;
392 BatteryNotifier& notifier(BatteryNotifier::getInstance());
393 if (oldUid != newUid) {
394 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800395 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700396 notifier.noteFlashlightOff(cameraId, oldUid);
397 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800398 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700399 notifier.noteFlashlightOn(cameraId, newUid);
400 }
401 iter->second.second = newUid;
402 } else {
403 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800404 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700405 notifier.noteFlashlightOn(cameraId, oldUid);
406 } else {
407 notifier.noteFlashlightOff(cameraId, oldUid);
408 }
409 }
410 }
411 }
412
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800413 broadcastTorchModeStatus(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800414}
415
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800416Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700417 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100418 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700419 switch (type) {
420 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800421 *numCameras = static_cast<int>(mNormalDeviceIds.size());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800422 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700423 case CAMERA_TYPE_ALL:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800424 *numCameras = mNumberOfCameras;
425 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700426 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800427 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700428 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800429 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
430 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700431 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800432 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700433}
434
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800435Status CameraService::getCameraInfo(int cameraId,
436 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700437 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100438 Mutex::Autolock l(mServiceLock);
439
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800440 if (!mInitialized) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800441 return STATUS_ERROR(ERROR_DISCONNECTED,
442 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700443 }
444
Mathias Agopian65ab4712010-07-14 17:59:35 -0700445 if (cameraId < 0 || cameraId >= mNumberOfCameras) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800446 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
447 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700448 }
449
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800450 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800451 status_t err = mCameraProviderManager->getCameraInfo(
452 cameraIdIntToStrLocked(cameraId), cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100453 if (err != OK) {
454 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
455 "Error retrieving camera info from device %d: %s (%d)", cameraId,
456 strerror(-err), err);
Ruben Brunkcc776712015-02-17 20:18:47 -0800457 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100458
Ruben Brunkcc776712015-02-17 20:18:47 -0800459 return ret;
460}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700461
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800462std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
463 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(mNormalDeviceIds.size())) {
464 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
465 __FUNCTION__, cameraIdInt, mNormalDeviceIds.size());
466 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800467 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800468
469 return mNormalDeviceIds[cameraIdInt];
470}
471
472String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
473 Mutex::Autolock lock(mServiceLock);
474 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800475}
476
477Status CameraService::getCameraCharacteristics(const String16& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800478 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700479 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700480 if (!cameraInfo) {
481 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800482 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700483 }
484
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800485 if (!mInitialized) {
486 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800487 return STATUS_ERROR(ERROR_DISCONNECTED,
488 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700489 }
490
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800491 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800492
Emilian Peevf53f66e2017-04-11 14:29:43 +0100493 status_t res = mCameraProviderManager->getCameraCharacteristics(
494 String8(cameraId).string(), cameraInfo);
495 if (res != OK) {
496 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
497 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
498 strerror(-res), res);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700499 }
Zhijun He2b59be82013-09-25 10:14:30 -0700500
501 return ret;
502}
503
Ruben Brunkcc776712015-02-17 20:18:47 -0800504int CameraService::getCallingPid() {
505 return IPCThreadState::self()->getCallingPid();
506}
507
508int CameraService::getCallingUid() {
509 return IPCThreadState::self()->getCallingUid();
510}
511
512String8 CameraService::getFormattedCurrentTime() {
513 time_t now = time(nullptr);
514 char formattedTime[64];
515 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
516 return String8(formattedTime);
517}
518
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800519Status CameraService::getCameraVendorTagDescriptor(
520 /*out*/
521 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700522 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800523 if (!mInitialized) {
524 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800525 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800526 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800527 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
528 if (globalDescriptor != nullptr) {
529 *desc = *(globalDescriptor.get());
530 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800531 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800532}
533
Emilian Peev71c73a22017-03-21 16:35:51 +0000534Status CameraService::getCameraVendorTagCache(
535 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
536 ATRACE_CALL();
537 if (!mInitialized) {
538 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
539 return STATUS_ERROR(ERROR_DISCONNECTED,
540 "Camera subsystem not available");
541 }
542 sp<VendorTagDescriptorCache> globalCache =
543 VendorTagDescriptorCache::getGlobalVendorTagCache();
544 if (globalCache != nullptr) {
545 *cache = *(globalCache.get());
546 }
547 return Status::ok();
548}
549
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800550int CameraService::getDeviceVersion(const String8& cameraId, int* facing) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700551 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800552
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800553 int deviceVersion = 0;
554
Emilian Peevf53f66e2017-04-11 14:29:43 +0100555 status_t res;
556 hardware::hidl_version maxVersion{0,0};
557 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
558 &maxVersion);
559 if (res != OK) return -1;
560 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800561
Emilian Peevf53f66e2017-04-11 14:29:43 +0100562 hardware::CameraInfo info;
563 if (facing) {
564 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800565 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100566 *facing = info.facing;
Igor Murashkin634a5152013-02-20 17:15:11 -0800567 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100568
Igor Murashkin634a5152013-02-20 17:15:11 -0800569 return deviceVersion;
570}
571
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800572Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700573 switch(err) {
574 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800575 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800576 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800577 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
578 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800579 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800580 return STATUS_ERROR(ERROR_DISCONNECTED,
581 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700582 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800583 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
584 "Camera HAL encountered error %d: %s",
585 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700586 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800587}
588
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800589Status CameraService::makeClient(const sp<CameraService>& cameraService,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800590 const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800591 int api1CameraId, int facing, int clientPid, uid_t clientUid, int servicePid,
592 bool legacyMode, int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
Ruben Brunkcc776712015-02-17 20:18:47 -0800593 /*out*/sp<BasicClient>* client) {
594
Ruben Brunkcc776712015-02-17 20:18:47 -0800595 if (halVersion < 0 || halVersion == deviceVersion) {
596 // Default path: HAL version is unspecified by caller, create CameraClient
597 // based on device version reported by the HAL.
598 switch(deviceVersion) {
599 case CAMERA_DEVICE_API_VERSION_1_0:
600 if (effectiveApiLevel == API_1) { // Camera1 API route
601 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800602 *client = new CameraClient(cameraService, tmp, packageName,
603 api1CameraId, facing, clientPid, clientUid,
604 getpid(), legacyMode);
Ruben Brunkcc776712015-02-17 20:18:47 -0800605 } else { // Camera2 API route
606 ALOGW("Camera using old HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800607 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800608 "Camera device \"%s\" HAL version %d does not support camera2 API",
609 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800610 }
611 break;
Ruben Brunkcc776712015-02-17 20:18:47 -0800612 case CAMERA_DEVICE_API_VERSION_3_0:
613 case CAMERA_DEVICE_API_VERSION_3_1:
614 case CAMERA_DEVICE_API_VERSION_3_2:
615 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -0700616 case CAMERA_DEVICE_API_VERSION_3_4:
Ruben Brunkcc776712015-02-17 20:18:47 -0800617 if (effectiveApiLevel == API_1) { // Camera1 API route
618 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800619 *client = new Camera2Client(cameraService, tmp, packageName,
620 cameraId, api1CameraId,
621 facing, clientPid, clientUid,
622 servicePid, legacyMode);
Ruben Brunkcc776712015-02-17 20:18:47 -0800623 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800624 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
625 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
626 *client = new CameraDeviceClient(cameraService, tmp, packageName, cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -0800627 facing, clientPid, clientUid, servicePid);
628 }
629 break;
630 default:
631 // Should not be reachable
632 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800633 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800634 "Camera device \"%s\" has unknown HAL version %d",
635 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800636 }
637 } else {
638 // A particular HAL version is requested by caller. Create CameraClient
639 // based on the requested HAL version.
640 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
641 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
642 // Only support higher HAL version device opened as HAL1.0 device.
643 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800644 *client = new CameraClient(cameraService, tmp, packageName,
645 api1CameraId, facing, clientPid, clientUid,
646 servicePid, legacyMode);
Ruben Brunkcc776712015-02-17 20:18:47 -0800647 } else {
648 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
649 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
650 " opened as HAL %x device", halVersion, deviceVersion,
651 CAMERA_DEVICE_API_VERSION_1_0);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800652 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800653 "Camera device \"%s\" (HAL version %d) cannot be opened as HAL version %d",
654 cameraId.string(), deviceVersion, halVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800655 }
656 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800657 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800658}
659
Ruben Brunk6267b532015-04-30 17:44:07 -0700660String8 CameraService::toString(std::set<userid_t> intSet) {
661 String8 s("");
662 bool first = true;
663 for (userid_t i : intSet) {
664 if (first) {
665 s.appendFormat("%d", i);
666 first = false;
667 } else {
668 s.appendFormat(", %d", i);
669 }
670 }
671 return s;
672}
673
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800674int32_t CameraService::mapToInterface(TorchModeStatus status) {
675 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
676 switch (status) {
677 case TorchModeStatus::NOT_AVAILABLE:
678 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
679 break;
680 case TorchModeStatus::AVAILABLE_OFF:
681 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
682 break;
683 case TorchModeStatus::AVAILABLE_ON:
684 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
685 break;
686 default:
687 ALOGW("Unknown new flash status: %d", status);
688 }
689 return serviceStatus;
690}
691
692CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
693 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
694 switch (status) {
695 case CameraDeviceStatus::NOT_PRESENT:
696 serviceStatus = StatusInternal::NOT_PRESENT;
697 break;
698 case CameraDeviceStatus::PRESENT:
699 serviceStatus = StatusInternal::PRESENT;
700 break;
701 case CameraDeviceStatus::ENUMERATING:
702 serviceStatus = StatusInternal::ENUMERATING;
703 break;
704 default:
705 ALOGW("Unknown new HAL device status: %d", status);
706 }
707 return serviceStatus;
708}
709
710int32_t CameraService::mapToInterface(StatusInternal status) {
711 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
712 switch (status) {
713 case StatusInternal::NOT_PRESENT:
714 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
715 break;
716 case StatusInternal::PRESENT:
717 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
718 break;
719 case StatusInternal::ENUMERATING:
720 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
721 break;
722 case StatusInternal::NOT_AVAILABLE:
723 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
724 break;
725 case StatusInternal::UNKNOWN:
726 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
727 break;
728 default:
729 ALOGW("Unknown new internal device status: %d", status);
730 }
731 return serviceStatus;
732}
733
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800734Status CameraService::initializeShimMetadata(int cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800735 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700736
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800737 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -0800738 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800739 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800740 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800741 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800742 sp<ICameraClient>{nullptr}, id, cameraId,
743 static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800744 internalPackageName, uid, USE_CALLING_PID,
745 API_1, /*legacyMode*/ false, /*shimUpdateOnly*/ true,
746 /*out*/ tmp)
747 ).isOk()) {
748 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -0700749 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800750 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700751}
752
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800753Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -0700754 /*out*/
755 CameraParameters* parameters) {
756
757 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
758
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800759 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -0700760
761 if (parameters == NULL) {
762 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800763 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700764 }
765
Ruben Brunkcc776712015-02-17 20:18:47 -0800766 String8 id = String8::format("%d", cameraId);
767
768 // Check if we already have parameters
769 {
770 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700771 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800772 auto cameraState = getCameraState(id);
773 if (cameraState == nullptr) {
774 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800775 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
776 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800777 }
778 CameraParameters p = cameraState->getShimParams();
779 if (!p.isEmpty()) {
780 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800781 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700782 }
783 }
784
Ruben Brunkcc776712015-02-17 20:18:47 -0800785 int64_t token = IPCThreadState::self()->clearCallingIdentity();
786 ret = initializeShimMetadata(cameraId);
787 IPCThreadState::self()->restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800788 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800789 // Error already logged by callee
790 return ret;
791 }
792
793 // Check for parameters again
794 {
795 // Scope for service lock
796 Mutex::Autolock lock(mServiceLock);
797 auto cameraState = getCameraState(id);
798 if (cameraState == nullptr) {
799 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800800 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
801 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -0700802 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800803 CameraParameters p = cameraState->getShimParams();
804 if (!p.isEmpty()) {
805 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800806 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700807 }
808 }
809
Ruben Brunkcc776712015-02-17 20:18:47 -0800810 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
811 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800812 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700813}
814
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800815// Can camera service trust the caller based on the calling UID?
816static bool isTrustedCallingUid(uid_t uid) {
817 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -0700818 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800819 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -0700820 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800821 return true;
822 default:
823 return false;
824 }
825}
826
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800827Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -0700828 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
829 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -0500830
Alex Deymo9c2a2c22016-08-25 11:59:14 -0700831#ifdef __BRILLO__
832 UNUSED(clientName8);
833 UNUSED(clientUid);
834 UNUSED(clientPid);
835 UNUSED(originalClientPid);
836#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -0700837 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
838 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800839 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -0800840 return allowed;
841 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -0700842#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -0800843
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800844 int callingPid = getCallingPid();
845
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800846 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800847 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
848 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800849 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
850 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -0700851 }
852
Ruben Brunkcc776712015-02-17 20:18:47 -0800853 if (getCameraState(cameraId) == nullptr) {
854 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
855 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800856 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
857 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700858 }
859
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800860 status_t err = checkIfDeviceIsUsable(cameraId);
861 if (err != NO_ERROR) {
862 switch(err) {
863 case -ENODEV:
864 case -EBUSY:
865 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
866 "No camera device with ID \"%s\" currently available", cameraId.string());
867 default:
868 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
869 "Unknown error connecting to ID \"%s\"", cameraId.string());
870 }
871 }
872 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -0800873}
874
Eino-Ville Talvala04926862016-03-02 15:42:53 -0800875Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -0700876 const String8& clientName8, int& clientUid, int& clientPid,
877 /*out*/int& originalClientPid) const {
Christopher Wiley0039bcf2016-02-05 10:29:50 -0800878 int callingPid = getCallingPid();
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800879 int callingUid = getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700880
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800881 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -0700882 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800883 clientUid = callingUid;
884 } else if (!isTrustedCallingUid(callingUid)) {
885 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
886 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800887 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
888 "Untrusted caller (calling PID %d, UID %d) trying to "
889 "forward camera access to camera %s for client %s (PID %d, UID %d)",
890 callingPid, callingUid, cameraId.string(),
891 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700892 }
893
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800894 // Check if we can trust clientPid
895 if (clientPid == USE_CALLING_PID) {
896 clientPid = callingPid;
897 } else if (!isTrustedCallingUid(callingUid)) {
898 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
899 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800900 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
901 "Untrusted caller (calling PID %d, UID %d) trying to "
902 "forward camera access to camera %s for client %s (PID %d, UID %d)",
903 callingPid, callingUid, cameraId.string(),
904 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800905 }
906
907 // If it's not calling from cameraserver, check the permission.
908 if (callingPid != getpid() &&
909 !checkPermission(String16("android.permission.CAMERA"), clientPid, clientUid)) {
910 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800911 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
912 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
913 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800914 }
915
Svet Ganova453d0d2018-01-11 15:37:58 -0800916 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -0700917 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Svet Ganova453d0d2018-01-11 15:37:58 -0800918 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
919 clientPid, clientUid);
920 return STATUS_ERROR_FMT(ERROR_DISABLED,
921 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background",
922 clientName8.string(), clientUid, clientPid, cameraId.string());
923 }
924
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -0700925 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
926 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -0700927 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -0700928 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700929
Ruben Brunk6267b532015-04-30 17:44:07 -0700930 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +0800931
Ruben Brunka8ca9152015-04-07 14:23:40 -0700932 // Only allow clients who are being used by the current foreground device user, unless calling
933 // from our own process.
Ruben Brunk6267b532015-04-30 17:44:07 -0700934 if (callingPid != getpid() && (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
935 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
936 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
937 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800938 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
939 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
940 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -0700941 }
942
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800943 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800944}
945
946status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
947 auto cameraState = getCameraState(cameraId);
948 int callingPid = getCallingPid();
949 if (cameraState == nullptr) {
950 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
951 cameraId.string());
952 return -ENODEV;
953 }
954
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800955 StatusInternal currentStatus = cameraState->getStatus();
956 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800957 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
958 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700959 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800960 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800961 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
962 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700963 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -0700964 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700965
Ruben Brunkcc776712015-02-17 20:18:47 -0800966 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -0800967}
968
Ruben Brunkcc776712015-02-17 20:18:47 -0800969void CameraService::finishConnectLocked(const sp<BasicClient>& client,
970 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -0800971
Ruben Brunkcc776712015-02-17 20:18:47 -0800972 // Make a descriptor for the incoming client
973 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
974 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
975
976 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
977 String8(client->getPackageName()));
978
979 if (evicted.size() > 0) {
980 // This should never happen - clients should already have been removed in disconnect
981 for (auto& i : evicted) {
982 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
983 __FUNCTION__, i->getKey().string());
984 }
985
986 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
987 __FUNCTION__);
988 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -0700989
990 // And register a death notification for the client callback. Do
991 // this last to avoid Binder policy where a nested Binder
992 // transaction might be pre-empted to service the client death
993 // notification if the client process dies before linkToDeath is
994 // invoked.
995 sp<IBinder> remoteCallback = client->getRemote();
996 if (remoteCallback != nullptr) {
997 remoteCallback->linkToDeath(this);
998 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800999}
1000
1001status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1002 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
1003 /*out*/
1004 sp<BasicClient>* client,
1005 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001006 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001007 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001008 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001009 DescriptorPtr clientDescriptor;
1010 {
1011 if (effectiveApiLevel == API_1) {
1012 // If we are using API1, any existing client for this camera ID with the same remote
1013 // should be returned rather than evicted to allow MediaRecorder to work properly.
1014
1015 auto current = mActiveClientManager.get(cameraId);
1016 if (current != nullptr) {
1017 auto clientSp = current->getValue();
1018 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001019 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1020 ALOGW("CameraService connect called from same client, but with a different"
1021 " API level, evicting prior client...");
1022 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001023 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001024 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001025 *client = clientSp;
1026 return NO_ERROR;
1027 }
1028 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001029 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001030 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001031
Ruben Brunkcc776712015-02-17 20:18:47 -08001032 // Get current active client PIDs
1033 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1034 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001035
Emilian Peev8131a262017-02-01 12:33:43 +00001036 std::vector<int> priorityScores(ownerPids.size());
1037 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001038
Emilian Peev8131a262017-02-01 12:33:43 +00001039 // Get priority scores of all active PIDs
1040 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1041 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1042 /*out*/&priorityScores[0]);
1043 if (err != OK) {
1044 ALOGE("%s: Priority score query failed: %d",
1045 __FUNCTION__, err);
1046 return err;
1047 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001048
Ruben Brunkcc776712015-02-17 20:18:47 -08001049 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001050 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001051 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001052 pidToPriorityMap.emplace(ownerPids[i],
1053 resource_policy::ClientPriority(priorityScores[i], states[i]));
Ruben Brunkcc776712015-02-17 20:18:47 -08001054 }
1055 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001056
Ruben Brunkcc776712015-02-17 20:18:47 -08001057 // Get state for the given cameraId
1058 auto state = getCameraState(cameraId);
1059 if (state == nullptr) {
1060 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1061 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001062 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001063 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001064 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001065
1066 // Make descriptor for incoming client
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001067 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001068 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1069 state->getConflicting(),
Emilian Peev8131a262017-02-01 12:33:43 +00001070 priorityScores[priorityScores.size() - 1],
1071 clientPid,
1072 states[states.size() - 1]);
Ruben Brunkcc776712015-02-17 20:18:47 -08001073
1074 // Find clients that would be evicted
1075 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1076
1077 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1078 // background, so we cannot do evictions
1079 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1080 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1081 " priority).", clientPid);
1082
1083 sp<BasicClient> clientSp = clientDescriptor->getValue();
1084 String8 curTime = getFormattedCurrentTime();
1085 auto incompatibleClients =
1086 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1087
1088 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001089 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001090 cameraId.string(), packageName.string(), clientPid,
Emilian Peev8131a262017-02-01 12:33:43 +00001091 priorityScores[priorityScores.size() - 1],
1092 states[states.size() - 1]);
Ruben Brunkcc776712015-02-17 20:18:47 -08001093
1094 for (auto& i : incompatibleClients) {
1095 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001096 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1097 i->getKey().string(),
1098 String8{i->getValue()->getPackageName()}.string(),
1099 i->getOwnerId(), i->getPriority().getScore(),
1100 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001101 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001102 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001103 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001104 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001105 }
1106
1107 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001108 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001109 mEventLog.add(msg);
1110
1111 return -EBUSY;
1112 }
1113
1114 for (auto& i : evicted) {
1115 sp<BasicClient> clientSp = i->getValue();
1116 if (clientSp.get() == nullptr) {
1117 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1118
1119 // TODO: Remove this
1120 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1121 __FUNCTION__);
1122 mActiveClientManager.remove(i);
1123 continue;
1124 }
1125
1126 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1127 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001128 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001129
Ruben Brunkcc776712015-02-17 20:18:47 -08001130 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001131 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001132 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1133 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001134 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001135 i->getOwnerId(), i->getPriority().getScore(),
1136 i->getPriority().getState(), cameraId.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001137 packageName.string(), clientPid,
Emilian Peev8131a262017-02-01 12:33:43 +00001138 priorityScores[priorityScores.size() - 1],
1139 states[states.size() - 1]));
Ruben Brunkcc776712015-02-17 20:18:47 -08001140
1141 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001142 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001143 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001144 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001145 }
1146
Ruben Brunkcc776712015-02-17 20:18:47 -08001147 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1148 // other clients from connecting in mServiceLockWrapper if held
1149 mServiceLock.unlock();
1150
1151 // Clear caller identity temporarily so client disconnect PID checks work correctly
1152 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1153
1154 // Destroy evicted clients
1155 for (auto& i : evictedClients) {
1156 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001157 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001158 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001159
1160 IPCThreadState::self()->restoreCallingIdentity(token);
1161
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001162 for (const auto& i : evictedClients) {
1163 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1164 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1165 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1166 if (ret == TIMED_OUT) {
1167 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1168 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1169 mActiveClientManager.toString().string());
1170 return -EBUSY;
1171 }
1172 if (ret != NO_ERROR) {
1173 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1174 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1175 ret, mActiveClientManager.toString().string());
1176 return ret;
1177 }
1178 }
1179
1180 evictedClients.clear();
1181
Ruben Brunkcc776712015-02-17 20:18:47 -08001182 // Once clients have been disconnected, relock
1183 mServiceLock.lock();
1184
1185 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1186 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1187 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001188 }
1189
Ruben Brunkcc776712015-02-17 20:18:47 -08001190 *partial = clientDescriptor;
1191 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001192}
1193
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001194Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001195 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001196 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001197 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001198 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001199 int clientPid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001200 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001201 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001202
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001203 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001204 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001205
1206 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001207 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001208 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001209 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, clientUid, clientPid, API_1,
1210 /*legacyMode*/ false, /*shimUpdateOnly*/ false,
1211 /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001212
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001213 if(!ret.isOk()) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001214 logRejected(id, getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001215 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001216 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001217 }
1218
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001219 *device = client;
1220 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001221}
1222
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001223Status CameraService::connectLegacy(
Zhijun Heb10cdad2014-06-16 16:38:35 -07001224 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001225 int api1CameraId, int halVersion,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001226 const String16& clientPackageName,
Zhijun Heb10cdad2014-06-16 16:38:35 -07001227 int clientUid,
1228 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001229 sp<ICamera>* device) {
Zhijun Heb10cdad2014-06-16 16:38:35 -07001230
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001231 ATRACE_CALL();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001232 String8 id = cameraIdIntToStr(api1CameraId);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001233
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001234 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001235 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001236 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId, halVersion,
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001237 clientPackageName, clientUid, USE_CALLING_PID, API_1,
1238 /*legacyMode*/ true, /*shimUpdateOnly*/ false,
1239 /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001240
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001241 if(!ret.isOk()) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001242 logRejected(id, getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001243 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001244 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001245 }
1246
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001247 *device = client;
1248 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001249}
1250
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001251Status CameraService::connectDevice(
1252 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001253 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001254 const String16& clientPackageName,
Ruben Brunkcc776712015-02-17 20:18:47 -08001255 int clientUid,
1256 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001257 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001258
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001259 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001260 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001261 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001262 sp<CameraDeviceClient> client = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001263 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001264 /*api1CameraId*/-1,
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001265 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName,
1266 clientUid, USE_CALLING_PID, API_2,
1267 /*legacyMode*/ false, /*shimUpdateOnly*/ false,
1268 /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001269
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001270 if(!ret.isOk()) {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001271 logRejected(id, getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001272 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001273 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001274 }
1275
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001276 *device = client;
1277 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001278}
1279
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001280template<class CALLBACK, class CLIENT>
1281Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001282 int api1CameraId, int halVersion, const String16& clientPackageName, int clientUid,
1283 int clientPid, apiLevel effectiveApiLevel, bool legacyMode, bool shimUpdateOnly,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001284 /*out*/sp<CLIENT>& device) {
1285 binder::Status ret = binder::Status::ok();
1286
1287 String8 clientName8(clientPackageName);
1288
1289 int originalClientPid = 0;
1290
1291 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) for HAL version %s and "
1292 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
1293 (halVersion == -1) ? "default" : std::to_string(halVersion).c_str(),
1294 static_cast<int>(effectiveApiLevel));
1295
1296 sp<CLIENT> client = nullptr;
1297 {
1298 // Acquire mServiceLock and prevent other clients from connecting
1299 std::unique_ptr<AutoConditionLock> lock =
1300 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1301
1302 if (lock == nullptr) {
1303 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1304 , clientPid);
1305 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1306 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1307 cameraId.string(), clientName8.string(), clientPid);
1308 }
1309
1310 // Enforce client permissions and do basic sanity checks
1311 if(!(ret = validateConnectLocked(cameraId, clientName8,
1312 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1313 return ret;
1314 }
1315
1316 // Check the shim parameters after acquiring lock, if they have already been updated and
1317 // we were doing a shim update, return immediately
1318 if (shimUpdateOnly) {
1319 auto cameraState = getCameraState(cameraId);
1320 if (cameraState != nullptr) {
1321 if (!cameraState->getShimParams().isEmpty()) return ret;
1322 }
1323 }
1324
1325 status_t err;
1326
1327 sp<BasicClient> clientTmp = nullptr;
1328 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1329 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
1330 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
1331 /*out*/&partial)) != NO_ERROR) {
1332 switch (err) {
1333 case -ENODEV:
1334 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1335 "No camera device with ID \"%s\" currently available",
1336 cameraId.string());
1337 case -EBUSY:
1338 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1339 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1340 cameraId.string());
1341 default:
1342 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1343 "Unexpected error %s (%d) opening camera \"%s\"",
1344 strerror(-err), err, cameraId.string());
1345 }
1346 }
1347
1348 if (clientTmp.get() != nullptr) {
1349 // Handle special case for API1 MediaRecorder where the existing client is returned
1350 device = static_cast<CLIENT*>(clientTmp.get());
1351 return ret;
1352 }
1353
1354 // give flashlight a chance to close devices if necessary.
1355 mFlashlight->prepareDeviceOpen(cameraId);
1356
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001357 int facing = -1;
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001358 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001359 if (facing == -1) {
1360 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1361 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1362 "Unable to get camera device \"%s\" facing", cameraId.string());
1363 }
1364
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001365 sp<BasicClient> tmp = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001366 if(!(ret = makeClient(this, cameraCb, clientPackageName,
1367 cameraId, api1CameraId, facing,
1368 clientPid, clientUid, getpid(), legacyMode,
1369 halVersion, deviceVersion, effectiveApiLevel,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001370 /*out*/&tmp)).isOk()) {
1371 return ret;
1372 }
1373 client = static_cast<CLIENT*>(tmp.get());
1374
1375 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1376 __FUNCTION__);
1377
Emilian Peevbd8c5032018-02-14 23:05:40 +00001378 err = client->initialize(mCameraProviderManager, mMonitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001379 if (err != OK) {
1380 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001381 // Errors could be from the HAL module open call or from AppOpsManager
1382 switch(err) {
1383 case BAD_VALUE:
1384 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1385 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1386 case -EBUSY:
1387 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1388 "Camera \"%s\" is already open", cameraId.string());
1389 case -EUSERS:
1390 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1391 "Too many cameras already open, cannot open camera \"%s\"",
1392 cameraId.string());
1393 case PERMISSION_DENIED:
1394 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1395 "No permission to open camera \"%s\"", cameraId.string());
1396 case -EACCES:
1397 return STATUS_ERROR_FMT(ERROR_DISABLED,
1398 "Camera \"%s\" disabled by policy", cameraId.string());
1399 case -ENODEV:
1400 default:
1401 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1402 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1403 strerror(-err), err);
1404 }
1405 }
1406
1407 // Update shim paremeters for legacy clients
1408 if (effectiveApiLevel == API_1) {
1409 // Assume we have always received a Client subclass for API1
1410 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1411 String8 rawParams = shimClient->getParameters();
1412 CameraParameters params(rawParams);
1413
1414 auto cameraState = getCameraState(cameraId);
1415 if (cameraState != nullptr) {
1416 cameraState->setShimParams(params);
1417 } else {
1418 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1419 __FUNCTION__, cameraId.string());
1420 }
1421 }
1422
1423 if (shimUpdateOnly) {
1424 // If only updating legacy shim parameters, immediately disconnect client
1425 mServiceLock.unlock();
1426 client->disconnect();
1427 mServiceLock.lock();
1428 } else {
1429 // Otherwise, add client to active clients list
1430 finishConnectLocked(client, partial);
1431 }
1432 } // lock is destroyed, allow further connect calls
1433
1434 // Important: release the mutex here so the client can call back into the service from its
1435 // destructor (can be at the end of the call)
1436 device = client;
1437 return ret;
1438}
1439
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001440Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001441 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001442 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001443
1444 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001445 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001446 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001447 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1448 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001449 }
1450
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001451 String8 id = String8(cameraId.string());
Ruben Brunk99e69712015-05-26 17:25:07 -07001452 int uid = getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001453
1454 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001455 auto state = getCameraState(id);
1456 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001457 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001458 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1459 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001460 }
1461
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001462 StatusInternal cameraStatus = state->getStatus();
1463 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001464 cameraStatus != StatusInternal::NOT_AVAILABLE) {
1465 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001466 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1467 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001468 }
1469
1470 {
1471 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001472 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001473 status_t err = getTorchStatusLocked(id, &status);
1474 if (err != OK) {
1475 if (err == NAME_NOT_FOUND) {
1476 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1477 "Camera \"%s\" does not have a flash unit", id.string());
1478 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001479 ALOGE("%s: getting current torch status failed for camera %s",
1480 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001481 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1482 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
1483 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001484 }
1485
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001486 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001487 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001488 ALOGE("%s: torch mode of camera %s is not available because "
1489 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001490 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1491 "Torch for camera \"%s\" is not available due to an existing camera user",
1492 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001493 } else {
1494 ALOGE("%s: torch mode of camera %s is not available due to "
1495 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001496 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1497 "Torch for camera \"%s\" is not available due to insufficient resources",
1498 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001499 }
1500 }
1501 }
1502
Ruben Brunk99e69712015-05-26 17:25:07 -07001503 {
1504 // Update UID map - this is used in the torch status changed callbacks, so must be done
1505 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001506 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001507 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1508 mTorchUidMap[id].first = uid;
1509 mTorchUidMap[id].second = uid;
1510 } else {
1511 // Set the pending UID
1512 mTorchUidMap[id].first = uid;
1513 }
1514 }
1515
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001516 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001517
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001518 if (err != OK) {
1519 int32_t errorCode;
1520 String8 msg;
1521 switch (err) {
1522 case -ENOSYS:
1523 msg = String8::format("Camera \"%s\" has no flashlight",
1524 id.string());
1525 errorCode = ERROR_ILLEGAL_ARGUMENT;
1526 break;
1527 default:
1528 msg = String8::format(
1529 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1530 id.string(), enabled, strerror(-err), err);
1531 errorCode = ERROR_INVALID_OPERATION;
1532 }
1533 ALOGE("%s: %s", __FUNCTION__, msg.string());
1534 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001535 }
1536
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001537 {
1538 // update the link to client's death
1539 Mutex::Autolock al(mTorchClientMapMutex);
1540 ssize_t index = mTorchClientMap.indexOfKey(id);
1541 if (enabled) {
1542 if (index == NAME_NOT_FOUND) {
1543 mTorchClientMap.add(id, clientBinder);
1544 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001545 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001546 mTorchClientMap.replaceValueAt(index, clientBinder);
1547 }
1548 clientBinder->linkToDeath(this);
1549 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001550 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001551 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001552 }
1553
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001554 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001555}
1556
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001557Status CameraService::notifySystemEvent(int32_t eventId,
1558 const std::vector<int32_t>& args) {
Jeongik Chacf461b22018-11-17 05:08:04 +09001559 const int pid = getCallingPid();
1560 const int selfPid = getpid();
1561
1562 // Permission checks
1563 if (pid != selfPid) {
1564 // Ensure we're being called by system_server, or similar process with
1565 // permissions to notify the camera service about system events
1566 if (!checkCallingPermission(
1567 String16("android.permission.CAMERA_SEND_SYSTEM_EVENTS"))) {
1568 const int uid = getCallingUid();
1569 ALOGE("Permission Denial: cannot send updates to camera service about system"
1570 " events from pid=%d, uid=%d", pid, uid);
1571 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1572 "No permission to send updates to camera service about system events"
1573 " from pid=%d, uid=%d", pid, uid);
1574 }
1575 }
1576
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001577 ATRACE_CALL();
1578
Ruben Brunk36597b22015-03-20 22:15:57 -07001579 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001580 case ICameraService::EVENT_USER_SWITCHED: {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07001581 // Try to register for UID policy updates, in case we're recovering
1582 // from a system server crash
1583 mUidPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001584 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07001585 break;
1586 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001587 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07001588 default: {
1589 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1590 eventId);
1591 break;
1592 }
1593 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001594 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07001595}
1596
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001597Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
1598 /*out*/
1599 std::vector<hardware::CameraStatus> *cameraStatuses) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001600 ATRACE_CALL();
1601
Igor Murashkinbfc99152013-02-27 12:55:20 -08001602 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08001603
Ruben Brunk3450ba72015-06-16 11:00:37 -07001604 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001605 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001606 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001607 }
1608
Igor Murashkinbfc99152013-02-27 12:55:20 -08001609 Mutex::Autolock lock(mServiceLock);
1610
Ruben Brunkcc776712015-02-17 20:18:47 -08001611 {
1612 Mutex::Autolock lock(mStatusListenerLock);
1613 for (auto& it : mListenerList) {
1614 if (IInterface::asBinder(it) == IInterface::asBinder(listener)) {
1615 ALOGW("%s: Tried to add listener %p which was already subscribed",
1616 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001617 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08001618 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001619 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001620
1621 mListenerList.push_back(listener);
Igor Murashkinbfc99152013-02-27 12:55:20 -08001622 }
1623
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001624 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07001625 {
Ruben Brunkcc776712015-02-17 20:18:47 -08001626 Mutex::Autolock lock(mCameraStatesLock);
1627 for (auto& i : mCameraStates) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001628 cameraStatuses->emplace_back(i.first, mapToInterface(i.second->getStatus()));
Igor Murashkincba2c162013-03-20 15:56:31 -07001629 }
1630 }
1631
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001632 /*
1633 * Immediately signal current torch status to this listener only
1634 * This may be a subset of all the devices, so don't include it in the response directly
1635 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001636 {
1637 Mutex::Autolock al(mTorchStatusMutex);
1638 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001639 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001640 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001641 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001642 }
1643
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001644 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08001645}
Ruben Brunkcc776712015-02-17 20:18:47 -08001646
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001647Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001648 ATRACE_CALL();
1649
Igor Murashkinbfc99152013-02-27 12:55:20 -08001650 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
1651
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001652 if (listener == 0) {
1653 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001654 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07001655 }
1656
Igor Murashkinbfc99152013-02-27 12:55:20 -08001657 Mutex::Autolock lock(mServiceLock);
1658
Ruben Brunkcc776712015-02-17 20:18:47 -08001659 {
1660 Mutex::Autolock lock(mStatusListenerLock);
1661 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
1662 if (IInterface::asBinder(*it) == IInterface::asBinder(listener)) {
1663 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001664 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001665 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001666 }
1667 }
1668
1669 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
1670 __FUNCTION__, listener.get());
1671
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001672 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08001673}
1674
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001675Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001676
1677 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001678 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1679
1680 if (parameters == NULL) {
1681 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001682 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001683 }
1684
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001685 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001686
1687 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001688 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07001689 // Error logged by caller
1690 return ret;
1691 }
1692
1693 String8 shimParamsString8 = shimParams.flatten();
1694 String16 shimParamsString16 = String16(shimParamsString8);
1695
1696 *parameters = shimParamsString16;
1697
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001698 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001699}
1700
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001701Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
1702 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001703 ATRACE_CALL();
1704
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001705 const String8 id = String8(cameraId);
1706
1707 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001708
1709 switch (apiVersion) {
1710 case API_VERSION_1:
1711 case API_VERSION_2:
1712 break;
1713 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001714 String8 msg = String8::format("Unknown API version %d", apiVersion);
1715 ALOGE("%s: %s", __FUNCTION__, msg.string());
1716 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001717 }
1718
Emilian Peev28ad2ea2017-02-07 16:14:32 +00001719 int deviceVersion = getDeviceVersion(id);
Igor Murashkin65d14b92014-06-17 12:03:20 -07001720 switch(deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001721 case CAMERA_DEVICE_API_VERSION_1_0:
1722 case CAMERA_DEVICE_API_VERSION_3_0:
1723 case CAMERA_DEVICE_API_VERSION_3_1:
1724 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001725 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
1726 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001727 *isSupported = false;
1728 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001729 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
1730 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001731 *isSupported = true;
1732 }
1733 break;
1734 case CAMERA_DEVICE_API_VERSION_3_2:
1735 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07001736 case CAMERA_DEVICE_API_VERSION_3_4:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001737 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
1738 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001739 *isSupported = true;
1740 break;
1741 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001742 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001743 ALOGE("%s: %s", __FUNCTION__, msg.string());
1744 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001745 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001746 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001747 String8 msg = String8::format("Unknown device version %x for device %s",
1748 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001749 ALOGE("%s: %s", __FUNCTION__, msg.string());
1750 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
1751 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07001752 }
1753
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001754 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001755}
1756
Ruben Brunkcc776712015-02-17 20:18:47 -08001757void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07001758 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001759 for (auto& i : mActiveClientManager.getAll()) {
1760 auto clientSp = i->getValue();
1761 if (clientSp.get() == client) {
1762 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08001763 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07001764 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001765}
1766
Ruben Brunkcc776712015-02-17 20:18:47 -08001767bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001768 bool ret = false;
1769 {
1770 // Acquire mServiceLock and prevent other clients from connecting
1771 std::unique_ptr<AutoConditionLock> lock =
1772 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08001773
Igor Murashkin634a5152013-02-20 17:15:11 -08001774
Ruben Brunkcc776712015-02-17 20:18:47 -08001775 std::vector<sp<BasicClient>> evicted;
1776 for (auto& i : mActiveClientManager.getAll()) {
1777 auto clientSp = i->getValue();
1778 if (clientSp.get() == nullptr) {
1779 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1780 mActiveClientManager.remove(i);
1781 continue;
1782 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08001783 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001784 mActiveClientManager.remove(i);
1785 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08001786
Ruben Brunkcc776712015-02-17 20:18:47 -08001787 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001788 clientSp->notifyError(
1789 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001790 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08001791 }
1792 }
1793
Ruben Brunkcc776712015-02-17 20:18:47 -08001794 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1795 // other clients from connecting in mServiceLockWrapper if held
1796 mServiceLock.unlock();
1797
Ruben Brunk36597b22015-03-20 22:15:57 -07001798 // Do not clear caller identity, remote caller should be client proccess
1799
Ruben Brunkcc776712015-02-17 20:18:47 -08001800 for (auto& i : evicted) {
1801 if (i.get() != nullptr) {
1802 i->disconnect();
1803 ret = true;
1804 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001805 }
1806
Ruben Brunkcc776712015-02-17 20:18:47 -08001807 // Reacquire mServiceLock
1808 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08001809
Ruben Brunkcc776712015-02-17 20:18:47 -08001810 } // lock is destroyed, allow further connect calls
1811
1812 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07001813}
1814
Ruben Brunkcc776712015-02-17 20:18:47 -08001815std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
1816 const String8& cameraId) const {
1817 std::shared_ptr<CameraState> state;
1818 {
1819 Mutex::Autolock lock(mCameraStatesLock);
1820 auto iter = mCameraStates.find(cameraId);
1821 if (iter != mCameraStates.end()) {
1822 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001823 }
1824 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001825 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001826}
1827
Ruben Brunkcc776712015-02-17 20:18:47 -08001828sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
1829 // Remove from active clients list
1830 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
1831 if (clientDescriptorPtr == nullptr) {
1832 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
1833 cameraId.string());
1834 return sp<BasicClient>{nullptr};
1835 }
1836
1837 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07001838}
1839
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001840void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07001841 // Acquire mServiceLock and prevent other clients from connecting
1842 std::unique_ptr<AutoConditionLock> lock =
1843 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1844
Ruben Brunk6267b532015-04-30 17:44:07 -07001845 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001846 for (size_t i = 0; i < newUserIds.size(); i++) {
1847 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001848 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001849 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07001850 return;
1851 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001852 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07001853 }
1854
Ruben Brunka8ca9152015-04-07 14:23:40 -07001855
Ruben Brunk6267b532015-04-30 17:44:07 -07001856 if (newAllowedUsers == mAllowedUsers) {
1857 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
1858 return;
1859 }
1860
1861 logUserSwitch(mAllowedUsers, newAllowedUsers);
1862
1863 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07001864
1865 // Current user has switched, evict all current clients.
1866 std::vector<sp<BasicClient>> evicted;
1867 for (auto& i : mActiveClientManager.getAll()) {
1868 auto clientSp = i->getValue();
1869
1870 if (clientSp.get() == nullptr) {
1871 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1872 continue;
1873 }
1874
Ruben Brunk6267b532015-04-30 17:44:07 -07001875 // Don't evict clients that are still allowed.
1876 uid_t clientUid = clientSp->getClientUid();
1877 userid_t clientUserId = multiuser_get_user_id(clientUid);
1878 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
1879 continue;
1880 }
1881
Ruben Brunk36597b22015-03-20 22:15:57 -07001882 evicted.push_back(clientSp);
1883
1884 String8 curTime = getFormattedCurrentTime();
1885
1886 ALOGE("Evicting conflicting client for camera ID %s due to user change",
1887 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07001888
Ruben Brunk36597b22015-03-20 22:15:57 -07001889 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001890 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001891 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
1892 " to user switch.", i->getKey().string(),
1893 String8{clientSp->getPackageName()}.string(),
1894 i->getOwnerId(), i->getPriority().getScore(),
1895 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07001896
1897 }
1898
1899 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1900 // blocking other clients from connecting in mServiceLockWrapper if held.
1901 mServiceLock.unlock();
1902
1903 // Clear caller identity temporarily so client disconnect PID checks work correctly
1904 int64_t token = IPCThreadState::self()->clearCallingIdentity();
1905
1906 for (auto& i : evicted) {
1907 i->disconnect();
1908 }
1909
1910 IPCThreadState::self()->restoreCallingIdentity(token);
1911
1912 // Reacquire mServiceLock
1913 mServiceLock.lock();
1914}
Ruben Brunkcc776712015-02-17 20:18:47 -08001915
Ruben Brunka8ca9152015-04-07 14:23:40 -07001916void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001917 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07001918 Mutex::Autolock l(mLogLock);
1919 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001920}
1921
Ruben Brunka8ca9152015-04-07 14:23:40 -07001922void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001923 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001924 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001925 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001926 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001927}
1928
1929void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001930 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001931 // Log the clients evicted
1932 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001933 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001934}
1935
1936void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001937 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07001938 // Log the client rejected
1939 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001940 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001941}
1942
Ruben Brunk6267b532015-04-30 17:44:07 -07001943void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
1944 const std::set<userid_t>& newUserIds) {
1945 String8 newUsers = toString(newUserIds);
1946 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08001947 if (oldUsers.size() == 0) {
1948 oldUsers = "<None>";
1949 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07001950 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08001951 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07001952 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07001953}
1954
1955void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
1956 // Log the device removal
1957 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
1958}
1959
1960void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
1961 // Log the device removal
1962 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
1963}
1964
1965void CameraService::logClientDied(int clientPid, const char* reason) {
1966 // Log the device removal
1967 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07001968}
1969
Eino-Ville Talvala1527f07e2015-04-07 15:55:31 -07001970void CameraService::logServiceError(const char* msg, int errorCode) {
1971 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08001972 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f07e2015-04-07 15:55:31 -07001973}
1974
Ruben Brunk36597b22015-03-20 22:15:57 -07001975status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
1976 uint32_t flags) {
1977
Ruben Brunk36597b22015-03-20 22:15:57 -07001978
Mathias Agopian65ab4712010-07-14 17:59:35 -07001979 // Permission checks
1980 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08001981 case SHELL_COMMAND_TRANSACTION: {
1982 int in = data.readFileDescriptor();
1983 int out = data.readFileDescriptor();
1984 int err = data.readFileDescriptor();
1985 int argc = data.readInt32();
1986 Vector<String16> args;
1987 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
1988 args.add(data.readString16());
1989 }
1990 sp<IBinder> unusedCallback;
1991 sp<IResultReceiver> resultReceiver;
1992 status_t status;
1993 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
1994 return status;
1995 }
1996 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
1997 return status;
1998 }
1999 status = shellCommand(in, out, err, args);
2000 if (resultReceiver != nullptr) {
2001 resultReceiver->send(status);
2002 }
2003 return NO_ERROR;
2004 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002005 }
2006
2007 return BnCameraService::onTransact(code, data, reply, flags);
2008}
2009
Mathias Agopian65ab4712010-07-14 17:59:35 -07002010// We share the media players for shutter and recording sound for all clients.
2011// A reference count is kept to determine when we will actually release the
2012// media players.
2013
Jaekyun Seokef498052018-03-23 13:09:44 +09002014sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
2015 sp<MediaPlayer> mp = new MediaPlayer();
2016 status_t error;
2017 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08002018 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09002019 error = mp->prepare();
2020 }
2021 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002022 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09002023 mp->disconnect();
2024 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002025 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002026 }
2027 return mp;
2028}
2029
username5755fea2018-12-27 09:48:08 +08002030void CameraService::increaseSoundRef() {
2031 Mutex::Autolock lock(mSoundLock);
2032 mSoundRef++;
2033}
2034
2035void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002036 ATRACE_CALL();
2037
username5755fea2018-12-27 09:48:08 +08002038 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
2039 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
2040 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
2041 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
2042 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2043 }
2044 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
2045 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
2046 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
2047 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002048 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08002049 }
2050 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
2051 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
2052 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
2053 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2054 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002055 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002056}
2057
username5755fea2018-12-27 09:48:08 +08002058void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002059 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002060 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002061 if (--mSoundRef) return;
2062
2063 for (int i = 0; i < NUM_SOUNDS; i++) {
2064 if (mSoundPlayer[i] != 0) {
2065 mSoundPlayer[i]->disconnect();
2066 mSoundPlayer[i].clear();
2067 }
2068 }
2069}
2070
2071void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002072 ATRACE_CALL();
2073
Mathias Agopian65ab4712010-07-14 17:59:35 -07002074 LOG1("playSound(%d)", kind);
2075 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002076 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002077 sp<MediaPlayer> player = mSoundPlayer[kind];
2078 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08002079 player->seekTo(0);
2080 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002081 }
2082}
2083
2084// ----------------------------------------------------------------------------
2085
2086CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002087 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002088 const String16& clientPackageName,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002089 const String8& cameraIdStr,
2090 int api1CameraId, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002091 int clientPid, uid_t clientUid,
2092 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002093 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08002094 IInterface::asBinder(cameraClient),
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002095 clientPackageName,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002096 cameraIdStr, cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002097 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002098 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002099 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08002100{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002101 int callingPid = getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002102 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002103
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002104 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002105
username5755fea2018-12-27 09:48:08 +08002106 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002107
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002108 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002109}
2110
Mathias Agopian65ab4712010-07-14 17:59:35 -07002111// tear down the client
2112CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002113 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08002114 mDestructionStarted = true;
2115
username5755fea2018-12-27 09:48:08 +08002116 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002117 // unconditionally disconnect. function is idempotent
2118 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002119}
2120
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002121sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
2122
Igor Murashkin634a5152013-02-20 17:15:11 -08002123CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002124 const sp<IBinder>& remoteCallback,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002125 const String16& clientPackageName,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002126 const String8& cameraIdStr, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002127 int clientPid, uid_t clientUid,
2128 int servicePid):
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002129 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing),
2130 mClientPackageName(clientPackageName), mClientPid(clientPid), mClientUid(clientUid),
2131 mServicePid(servicePid),
2132 mDisconnected(false),
2133 mRemoteBinder(remoteCallback)
Igor Murashkin634a5152013-02-20 17:15:11 -08002134{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002135 if (sCameraService == nullptr) {
2136 sCameraService = cameraService;
2137 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002138 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08002139 mDestructionStarted = false;
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08002140
2141 // In some cases the calling code has no access to the package it runs under.
2142 // For example, NDK camera API.
2143 // In this case we will get the packages for the calling UID and pick the first one
2144 // for attributing the app op. This will work correctly for runtime permissions
2145 // as for legacy apps we will toggle the app op for all packages in the UID.
2146 // The caveat is that the operation may be attributed to the wrong package and
2147 // stats based on app ops may be slightly off.
2148 if (mClientPackageName.size() <= 0) {
2149 sp<IServiceManager> sm = defaultServiceManager();
2150 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2151 if (binder == 0) {
2152 ALOGE("Cannot get permission service");
2153 // Leave mClientPackageName unchanged (empty) and the further interaction
2154 // with camera will fail in BasicClient::startCameraOps
2155 return;
2156 }
2157
2158 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2159 Vector<String16> packages;
2160
2161 permCtrl->getPackagesForUid(mClientUid, packages);
2162
2163 if (packages.isEmpty()) {
2164 ALOGE("No packages for calling UID");
2165 // Leave mClientPackageName unchanged (empty) and the further interaction
2166 // with camera will fail in BasicClient::startCameraOps
2167 return;
2168 }
2169 mClientPackageName = packages[0];
2170 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002171}
2172
2173CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002174 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08002175 mDestructionStarted = true;
2176}
2177
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002178binder::Status CameraService::BasicClient::disconnect() {
2179 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002180 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002181 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07002182 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002183 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002184
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002185 sCameraService->removeByClient(this);
2186 sCameraService->logDisconnected(mCameraIdStr, mClientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002187 String8(mClientPackageName));
Ruben Brunkcc776712015-02-17 20:18:47 -08002188
2189 sp<IBinder> remote = getRemote();
2190 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002191 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08002192 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002193
2194 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07002195 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002196 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
2197 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
2198 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002199
Igor Murashkincba2c162013-03-20 15:56:31 -07002200 // client shouldn't be able to call into us anymore
2201 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002202
2203 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08002204}
2205
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002206status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2207 // No dumping of clients directly over Binder,
2208 // must go through CameraService::dump
2209 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
2210 IPCThreadState::self()->getCallingUid(), NULL, 0);
2211 return OK;
2212}
2213
Ruben Brunkcc776712015-02-17 20:18:47 -08002214String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002215 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08002216}
2217
2218
2219int CameraService::BasicClient::getClientPid() const {
2220 return mClientPid;
2221}
2222
Ruben Brunk6267b532015-04-30 17:44:07 -07002223uid_t CameraService::BasicClient::getClientUid() const {
2224 return mClientUid;
2225}
2226
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002227bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2228 // Defaults to API2.
2229 return level == API_2;
2230}
2231
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002232status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002233 ATRACE_CALL();
2234
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002235 int32_t res;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002236 // Notify app ops that the camera is not available
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002237 mOpsCallback = new OpsCallback(this);
2238
Igor Murashkine6800ce2013-03-04 17:25:57 -08002239 {
2240 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002241 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002242 }
2243
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002244 mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002245 mClientPackageName, mOpsCallback);
Svet Ganov1d519102018-02-26 10:48:14 -08002246 res = mAppOpsManager.startOpNoThrow(AppOpsManager::OP_CAMERA,
2247 mClientUid, mClientPackageName, /*startIfModeDefault*/ false);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002248
Svetoslav28e8ef72015-05-11 19:21:31 -07002249 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002250 ALOGI("Camera %s: Access for \"%s\" has been revoked",
2251 mCameraIdStr.string(), String8(mClientPackageName).string());
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002252 return PERMISSION_DENIED;
2253 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002254
Svetoslav28e8ef72015-05-11 19:21:31 -07002255 if (res == AppOpsManager::MODE_IGNORED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002256 ALOGI("Camera %s: Access for \"%s\" has been restricted",
2257 mCameraIdStr.string(), String8(mClientPackageName).string());
Eino-Ville Talvalae3afb2c2015-06-03 16:03:30 -07002258 // Return the same error as for device policy manager rejection
2259 return -EACCES;
Svetoslav28e8ef72015-05-11 19:21:31 -07002260 }
2261
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002262 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002263
2264 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002265 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002266
Emilian Peev573291c2018-02-10 02:10:56 +00002267 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2268 if (canCastToApiClient(API_2)) {
2269 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2270 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002271 // Transition device state to OPEN
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002272 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
Emilian Peev573291c2018-02-10 02:10:56 +00002273 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002274
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002275 return OK;
2276}
2277
2278status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002279 ATRACE_CALL();
2280
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002281 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002282 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002283 // Notify app ops that the camera is available again
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002284 mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002285 mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002286 mOpsActive = false;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002287
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002288 // This function is called when a client disconnects. This should
2289 // release the camera, but actually only if it was in a proper
2290 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002291 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002292 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002293
Ruben Brunkcc776712015-02-17 20:18:47 -08002294 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002295 sCameraService->updateStatus(StatusInternal::PRESENT,
2296 mCameraIdStr, rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002297
Emilian Peev573291c2018-02-10 02:10:56 +00002298 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2299 if (canCastToApiClient(API_2)) {
2300 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2301 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002302 // Transition device state to CLOSED
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002303 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
Emilian Peev573291c2018-02-10 02:10:56 +00002304 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002305 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002306 // Always stop watching, even if no camera op is active
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002307 if (mOpsCallback != NULL) {
2308 mAppOpsManager.stopWatchingMode(mOpsCallback);
2309 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002310 mOpsCallback.clear();
2311
2312 return OK;
2313}
2314
2315void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002316 ATRACE_CALL();
2317
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002318 String8 name(packageName);
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002319 String8 myName(mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002320
2321 if (op != AppOpsManager::OP_CAMERA) {
2322 ALOGW("Unexpected app ops notification received: %d", op);
2323 return;
2324 }
2325
2326 int32_t res;
2327 res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002328 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002329 ALOGV("checkOp returns: %d, %s ", res,
2330 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
2331 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
2332 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
2333 "UNKNOWN");
2334
2335 if (res != AppOpsManager::MODE_ALLOWED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002336 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002337 myName.string());
Svet Ganova453d0d2018-01-11 15:37:58 -08002338 block();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002339 }
2340}
2341
Svet Ganova453d0d2018-01-11 15:37:58 -08002342void CameraService::BasicClient::block() {
2343 ATRACE_CALL();
2344
2345 // Reset the client PID to allow server-initiated disconnect,
2346 // and to prevent further calls by client.
2347 mClientPid = getCallingPid();
2348 CaptureResultExtras resultExtras; // a dummy result (invalid)
2349 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
2350 disconnect();
2351}
2352
Mathias Agopian65ab4712010-07-14 17:59:35 -07002353// ----------------------------------------------------------------------------
2354
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002355void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07002356 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002357 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07002358 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07002359 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
2360 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
2361 api1ErrorCode = CAMERA_ERROR_DISABLED;
2362 }
2363 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07002364 } else {
2365 ALOGE("mRemoteCallback is NULL!!");
2366 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002367}
2368
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002369// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002370binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002371 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002372 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08002373}
2374
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002375bool CameraService::Client::canCastToApiClient(apiLevel level) const {
2376 return level == API_1;
2377}
2378
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002379CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
2380 mClient(client) {
2381}
2382
2383void CameraService::Client::OpsCallback::opChanged(int32_t op,
2384 const String16& packageName) {
2385 sp<BasicClient> client = mClient.promote();
2386 if (client != NULL) {
2387 client->opChanged(op, packageName);
2388 }
2389}
2390
Mathias Agopian65ab4712010-07-14 17:59:35 -07002391// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08002392// UidPolicy
2393// ----------------------------------------------------------------------------
2394
2395void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002396 Mutex::Autolock _l(mUidLock);
2397
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002398 if (mRegistered) return;
Steven Moreland6a9fc9e2019-07-02 15:59:07 -07002399 status_t res = mAm.linkToDeath(this);
2400 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08002401 | ActivityManager::UID_OBSERVER_IDLE
2402 | ActivityManager::UID_OBSERVER_ACTIVE,
2403 ActivityManager::PROCESS_STATE_UNKNOWN,
2404 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002405 if (res == OK) {
2406 mRegistered = true;
2407 ALOGV("UidPolicy: Registered with ActivityManager");
2408 }
Svet Ganova453d0d2018-01-11 15:37:58 -08002409}
2410
2411void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002412 Mutex::Autolock _l(mUidLock);
2413
Steven Moreland6a9fc9e2019-07-02 15:59:07 -07002414 mAm.unregisterUidObserver(this);
2415 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002416 mRegistered = false;
2417 mActiveUids.clear();
2418 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08002419}
2420
2421void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
2422 onUidIdle(uid, disabled);
2423}
2424
2425void CameraService::UidPolicy::onUidActive(uid_t uid) {
2426 Mutex::Autolock _l(mUidLock);
2427 mActiveUids.insert(uid);
2428}
2429
2430void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
2431 bool deleted = false;
2432 {
2433 Mutex::Autolock _l(mUidLock);
2434 if (mActiveUids.erase(uid) > 0) {
2435 deleted = true;
2436 }
2437 }
2438 if (deleted) {
2439 sp<CameraService> service = mService.promote();
2440 if (service != nullptr) {
2441 service->blockClientsForUid(uid);
2442 }
2443 }
2444}
2445
Svet Ganov7b4ab782018-03-25 12:48:10 -07002446bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002447 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07002448 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08002449}
2450
Eino-Ville Talvala91175d92018-08-20 10:27:58 -07002451static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
2452static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganovbd39b492018-06-08 15:03:46 -07002453
Svet Ganov7b4ab782018-03-25 12:48:10 -07002454bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002455 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002456 // If activity manager is unreachable, assume everything is active
2457 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002458 return true;
2459 }
2460 auto it = mOverrideUids.find(uid);
2461 if (it != mOverrideUids.end()) {
2462 return it->second;
2463 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07002464 bool active = mActiveUids.find(uid) != mActiveUids.end();
2465 if (!active) {
2466 // We want active UIDs to always access camera with their first attempt since
2467 // there is no guarantee the app is robustly written and would retry getting
2468 // the camera on failure. The inverse case is not a problem as we would take
2469 // camera away soon once we get the callback that the uid is no longer active.
2470 ActivityManager am;
2471 // Okay to access with a lock held as UID changes are dispatched without
2472 // a lock and we are a higher level component.
Svet Ganovbd39b492018-06-08 15:03:46 -07002473 int64_t startTimeMillis = 0;
2474 do {
2475 // TODO: Fix this b/109950150!
2476 // Okay this is a hack. There is a race between the UID turning active and
2477 // activity being resumed. The proper fix is very risky, so we temporary add
2478 // some polling which should happen pretty rarely anyway as the race is hard
2479 // to hit.
Eino-Ville Talvala91175d92018-08-20 10:27:58 -07002480 active = mActiveUids.find(uid) != mActiveUids.end();
2481 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganovbd39b492018-06-08 15:03:46 -07002482 if (active) {
2483 break;
2484 }
2485 if (startTimeMillis <= 0) {
2486 startTimeMillis = uptimeMillis();
2487 }
2488 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala91175d92018-08-20 10:27:58 -07002489 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganovbd39b492018-06-08 15:03:46 -07002490 if (remainingTimeMillis <= 0) {
2491 break;
2492 }
Eino-Ville Talvala91175d92018-08-20 10:27:58 -07002493 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
2494
2495 mUidLock.unlock();
Svet Ganovbd39b492018-06-08 15:03:46 -07002496 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala91175d92018-08-20 10:27:58 -07002497 mUidLock.lock();
Svet Ganovbd39b492018-06-08 15:03:46 -07002498 } while (true);
2499
Svet Ganov7b4ab782018-03-25 12:48:10 -07002500 if (active) {
2501 // Now that we found out the UID is actually active, cache that
2502 mActiveUids.insert(uid);
2503 }
2504 }
2505 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08002506}
2507
Svet Ganov7b4ab782018-03-25 12:48:10 -07002508void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
2509 String16 callingPackage, bool active) {
2510 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08002511}
2512
Svet Ganov7b4ab782018-03-25 12:48:10 -07002513void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
2514 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08002515}
2516
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002517void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
2518 Mutex::Autolock _l(mUidLock);
2519 ALOGV("UidPolicy: ActivityManager has died");
2520 mRegistered = false;
2521 mActiveUids.clear();
2522}
2523
Svet Ganov7b4ab782018-03-25 12:48:10 -07002524void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
2525 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002526 bool wasActive = false;
2527 bool isActive = false;
2528 {
2529 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07002530 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08002531 mOverrideUids.erase(uid);
2532 if (insert) {
2533 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
2534 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07002535 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08002536 }
2537 if (wasActive != isActive && !isActive) {
2538 sp<CameraService> service = mService.promote();
2539 if (service != nullptr) {
2540 service->blockClientsForUid(uid);
2541 }
2542 }
2543}
2544
2545// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08002546// CameraState
2547// ----------------------------------------------------------------------------
2548
2549CameraService::CameraState::CameraState(const String8& id, int cost,
2550 const std::set<String8>& conflicting) : mId(id),
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002551 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08002552
2553CameraService::CameraState::~CameraState() {}
2554
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002555CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08002556 Mutex::Autolock lock(mStatusLock);
2557 return mStatus;
2558}
2559
2560CameraParameters CameraService::CameraState::getShimParams() const {
2561 return mShimParams;
2562}
2563
2564void CameraService::CameraState::setShimParams(const CameraParameters& params) {
2565 mShimParams = params;
2566}
2567
2568int CameraService::CameraState::getCost() const {
2569 return mCost;
2570}
2571
2572std::set<String8> CameraService::CameraState::getConflicting() const {
2573 return mConflicting;
2574}
2575
2576String8 CameraService::CameraState::getId() const {
2577 return mId;
2578}
2579
2580// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07002581// ClientEventListener
2582// ----------------------------------------------------------------------------
2583
2584void CameraService::ClientEventListener::onClientAdded(
2585 const resource_policy::ClientDescriptor<String8,
2586 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07002587 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07002588 if (basicClient.get() != nullptr) {
2589 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2590 notifier.noteStartCamera(descriptor.getKey(),
2591 static_cast<int>(basicClient->getClientUid()));
2592 }
2593}
2594
2595void CameraService::ClientEventListener::onClientRemoved(
2596 const resource_policy::ClientDescriptor<String8,
2597 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07002598 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07002599 if (basicClient.get() != nullptr) {
2600 BatteryNotifier& notifier(BatteryNotifier::getInstance());
2601 notifier.noteStopCamera(descriptor.getKey(),
2602 static_cast<int>(basicClient->getClientUid()));
2603 }
2604}
2605
2606
2607// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08002608// CameraClientManager
2609// ----------------------------------------------------------------------------
2610
Ruben Brunk99e69712015-05-26 17:25:07 -07002611CameraService::CameraClientManager::CameraClientManager() {
2612 setListener(std::make_shared<ClientEventListener>());
2613}
2614
Ruben Brunkcc776712015-02-17 20:18:47 -08002615CameraService::CameraClientManager::~CameraClientManager() {}
2616
2617sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
2618 const String8& id) const {
2619 auto descriptor = get(id);
2620 if (descriptor == nullptr) {
2621 return sp<BasicClient>{nullptr};
2622 }
2623 return descriptor->getValue();
2624}
2625
2626String8 CameraService::CameraClientManager::toString() const {
2627 auto all = getAll();
2628 String8 ret("[");
2629 bool hasAny = false;
2630 for (auto& i : all) {
2631 hasAny = true;
2632 String8 key = i->getKey();
2633 int32_t cost = i->getCost();
2634 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00002635 int32_t score = i->getPriority().getScore();
2636 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08002637 auto conflicting = i->getConflicting();
2638 auto clientSp = i->getValue();
2639 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002640 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08002641 if (clientSp.get() != nullptr) {
2642 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07002643 uid_t clientUid = clientSp->getClientUid();
2644 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002645 }
Emilian Peev8131a262017-02-01 12:33:43 +00002646 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
2647 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08002648
Ruben Brunk6267b532015-04-30 17:44:07 -07002649 if (clientSp.get() != nullptr) {
2650 ret.appendFormat("User Id: %d, ", clientUserId);
2651 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002652 if (packageName.size() != 0) {
2653 ret.appendFormat("Client Package Name: %s", packageName.string());
2654 }
2655
2656 ret.append(", Conflicting Client Devices: {");
2657 for (auto& j : conflicting) {
2658 ret.appendFormat("%s, ", j.string());
2659 }
2660 ret.append("})");
2661 }
2662 if (hasAny) ret.append("\n");
2663 ret.append("]\n");
2664 return ret;
2665}
2666
2667CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2668 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00002669 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
2670 int32_t state) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002671
2672 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Emilian Peev8131a262017-02-01 12:33:43 +00002673 key, value, cost, conflictingKeys, score, ownerId, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08002674}
2675
2676CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2677 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
2678 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00002679 partial->getConflicting(), partial->getPriority().getScore(),
2680 partial->getOwnerId(), partial->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002681}
2682
2683// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07002684
2685static const int kDumpLockRetries = 50;
2686static const int kDumpLockSleep = 60000;
2687
2688static bool tryLock(Mutex& mutex)
2689{
2690 bool locked = false;
2691 for (int i = 0; i < kDumpLockRetries; ++i) {
2692 if (mutex.tryLock() == NO_ERROR) {
2693 locked = true;
2694 break;
2695 }
2696 usleep(kDumpLockSleep);
2697 }
2698 return locked;
2699}
2700
2701status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002702 ATRACE_CALL();
2703
Mathias Agopian65ab4712010-07-14 17:59:35 -07002704 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002705 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07002706 getCallingPid(),
2707 getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002708 return NO_ERROR;
2709 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002710 bool locked = tryLock(mServiceLock);
2711 // failed to lock - CameraService is probably deadlocked
2712 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002713 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002714 }
Eino-Ville Talvala1527f07e2015-04-07 15:55:31 -07002715
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002716 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002717 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07002718
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002719 // Dump event log for error information
Eino-Ville Talvala1527f07e2015-04-07 15:55:31 -07002720 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08002721
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002722 if (locked) mServiceLock.unlock();
2723 return NO_ERROR;
2724 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002725 dprintf(fd, "\n== Service global info: ==\n\n");
2726 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002727 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
2728 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
2729 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
2730 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002731 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002732 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
2733 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002734
2735 dumpEventLog(fd);
2736
2737 bool stateLocked = tryLock(mCameraStatesLock);
2738 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002739 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002740 }
2741
Emilian Peevbd8c5032018-02-14 23:05:40 +00002742 int argSize = args.size();
2743 for (int i = 0; i < argSize; i++) {
2744 if (args[i] == TagMonitor::kMonitorOption) {
2745 if (i + 1 < argSize) {
2746 mMonitorTags = String8(args[i + 1]);
2747 }
2748 break;
2749 }
2750 }
2751
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002752 for (auto& state : mCameraStates) {
2753 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002754
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002755 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002756
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002757 CameraParameters p = state.second->getShimParams();
2758 if (!p.isEmpty()) {
2759 dprintf(fd, " Camera1 API shim is using parameters:\n ");
2760 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002761 }
2762
2763 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08002764 if (clientDescriptor != nullptr) {
2765 dprintf(fd, " Device %s is open. Client instance dump:\n",
2766 cameraId.string());
2767 dprintf(fd, " Client priority score: %d state: %d\n",
2768 clientDescriptor->getPriority().getScore(),
2769 clientDescriptor->getPriority().getState());
2770 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
2771
2772 auto client = clientDescriptor->getValue();
2773 dprintf(fd, " Client package: %s\n",
2774 String8(client->getPackageName()).string());
2775
2776 client->dumpClient(fd, args);
2777 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002778 dprintf(fd, " Device %s is closed, no client instance\n",
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002779 cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002780 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002781
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002782 }
2783
2784 if (stateLocked) mCameraStatesLock.unlock();
2785
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002786 if (locked) mServiceLock.unlock();
2787
Emilian Peevf53f66e2017-04-11 14:29:43 +01002788 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002789
2790 dprintf(fd, "\n== Vendor tags: ==\n\n");
2791
2792 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
2793 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00002794 sp<VendorTagDescriptorCache> cache =
2795 VendorTagDescriptorCache::getGlobalVendorTagCache();
2796 if (cache == NULL) {
2797 dprintf(fd, "No vendor tags.\n");
2798 } else {
2799 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
2800 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002801 } else {
2802 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
2803 }
2804
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002805 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002806 dprintf(fd, "\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002807 camera3::CameraTraces::dump(fd, args);
2808
2809 // Process dump arguments, if any
2810 int n = args.size();
2811 String16 verboseOption("-v");
2812 String16 unreachableOption("--unreachable");
2813 for (int i = 0; i < n; i++) {
2814 if (args[i] == verboseOption) {
2815 // change logging level
2816 if (i + 1 >= n) continue;
2817 String8 levelStr(args[i+1]);
2818 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002819 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002820 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002821 } else if (args[i] == unreachableOption) {
2822 // Dump memory analysis
2823 // TODO - should limit be an argument parameter?
2824 UnreachableMemoryInfo info;
2825 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
2826 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002827 dprintf(fd, "\n== Unable to dump unreachable memory. "
2828 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002829 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002830 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08002831 std::string s = info.ToString(/*log_contents*/ true);
2832 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002833 }
2834 }
2835 }
2836 return NO_ERROR;
2837}
2838
Eino-Ville Talvala1527f07e2015-04-07 15:55:31 -07002839void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002840 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f07e2015-04-07 15:55:31 -07002841
2842 Mutex::Autolock l(mLogLock);
2843 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002844 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f07e2015-04-07 15:55:31 -07002845 }
2846
2847 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002848 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f07e2015-04-07 15:55:31 -07002849 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002850 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f07e2015-04-07 15:55:31 -07002851 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002852 dprintf(fd, "\n");
Eino-Ville Talvala1527f07e2015-04-07 15:55:31 -07002853}
2854
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002855void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002856 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002857 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
2858 if (mTorchClientMap[i] == who) {
2859 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002860 String8 cameraId = mTorchClientMap.keyAt(i);
2861 status_t res = mFlashlight->setTorchMode(cameraId, false);
2862 if (res) {
2863 ALOGE("%s: torch client died but couldn't turn off torch: "
2864 "%s (%d)", __FUNCTION__, strerror(-res), res);
2865 return;
2866 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002867 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002868 break;
2869 }
2870 }
2871}
2872
Ruben Brunkcc776712015-02-17 20:18:47 -08002873/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002874
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002875 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07002876 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
2877 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07002878 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002879 // PID here is approximate and can be wrong.
Ruben Brunka8ca9152015-04-07 14:23:40 -07002880 logClientDied(getCallingPid(), String8("Binder died unexpectedly"));
2881
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002882 // check torch client
2883 handleTorchClientBinderDied(who);
2884
2885 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08002886 if(!evictClientIdByRemote(who)) {
2887 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002888 return;
2889 }
2890
Ruben Brunkcc776712015-02-17 20:18:47 -08002891 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
2892 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07002893}
2894
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002895void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002896 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08002897}
2898
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002899void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
2900 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002901 // Do not lock mServiceLock here or can get into a deadlock from
2902 // connect() -> disconnect -> updateStatus
2903
2904 auto state = getCameraState(cameraId);
2905
2906 if (state == nullptr) {
2907 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
2908 cameraId.string());
2909 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07002910 }
2911
Ruben Brunkcc776712015-02-17 20:18:47 -08002912 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
2913 // of the listeners with both the mStatusStatus and mStatusListenerLock held
2914 state->updateStatus(status, cameraId, rejectSourceStates, [this]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002915 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002916
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002917 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002918 // Update torch status if it has a flash unit.
2919 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002920 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002921 if (getTorchStatusLocked(cameraId, &torchStatus) !=
2922 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002923 TorchModeStatus newTorchStatus =
2924 status == StatusInternal::PRESENT ?
2925 TorchModeStatus::AVAILABLE_OFF :
2926 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002927 if (torchStatus != newTorchStatus) {
2928 onTorchStatusChangedLocked(cameraId, newTorchStatus);
2929 }
2930 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002931 }
2932
2933 Mutex::Autolock lock(mStatusListenerLock);
2934
2935 for (auto& listener : mListenerList) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002936 listener->onStatusChanged(mapToInterface(status), String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08002937 }
2938 });
Igor Murashkincba2c162013-03-20 15:56:31 -07002939}
2940
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002941template<class Func>
2942void CameraService::CameraState::updateStatus(StatusInternal status,
2943 const String8& cameraId,
2944 std::initializer_list<StatusInternal> rejectSourceStates,
2945 Func onStatusUpdatedLocked) {
2946 Mutex::Autolock lock(mStatusLock);
2947 StatusInternal oldStatus = mStatus;
2948 mStatus = status;
2949
2950 if (oldStatus == status) {
2951 return;
2952 }
2953
2954 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
2955 cameraId.string(), oldStatus, status);
2956
2957 if (oldStatus == StatusInternal::NOT_PRESENT &&
2958 (status != StatusInternal::PRESENT &&
2959 status != StatusInternal::ENUMERATING)) {
2960
2961 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
2962 __FUNCTION__);
2963 mStatus = oldStatus;
2964 return;
2965 }
2966
2967 /**
2968 * Sometimes we want to conditionally do a transition.
2969 * For example if a client disconnects, we want to go to PRESENT
2970 * only if we weren't already in NOT_PRESENT or ENUMERATING.
2971 */
2972 for (auto& rejectStatus : rejectSourceStates) {
2973 if (oldStatus == rejectStatus) {
2974 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
2975 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
2976 mStatus = oldStatus;
2977 return;
2978 }
2979 }
2980
2981 onStatusUpdatedLocked(cameraId, status);
2982}
2983
Eino-Ville Talvalae8c96c72017-06-27 12:24:07 -07002984void CameraService::updateProxyDeviceState(int newState,
Emilian Peev573291c2018-02-10 02:10:56 +00002985 const String8& cameraId, int facing, const String16& clientName, int apiLevel) {
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002986 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
2987 if (proxyBinder == nullptr) return;
2988 String16 id(cameraId);
Emilian Peev573291c2018-02-10 02:10:56 +00002989 proxyBinder->notifyCameraState(id, newState, facing, clientName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002990}
2991
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002992status_t CameraService::getTorchStatusLocked(
2993 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002994 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002995 if (!status) {
2996 return BAD_VALUE;
2997 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002998 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2999 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003000 // invalid camera ID or the camera doesn't have a flash unit
3001 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003002 }
3003
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003004 *status = mTorchStatusMap.valueAt(index);
3005 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003006}
3007
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003008status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003009 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003010 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3011 if (index == NAME_NOT_FOUND) {
3012 return BAD_VALUE;
3013 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003014 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003015
3016 return OK;
3017}
3018
Svet Ganova453d0d2018-01-11 15:37:58 -08003019void CameraService::blockClientsForUid(uid_t uid) {
3020 const auto clients = mActiveClientManager.getAll();
3021 for (auto& current : clients) {
3022 if (current != nullptr) {
3023 const auto basicClient = current->getValue();
3024 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
3025 basicClient->block();
3026 }
3027 }
3028 }
3029}
3030
3031// NOTE: This is a remote API - make sure all args are validated
3032status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
3033 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
3034 return PERMISSION_DENIED;
3035 }
3036 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
3037 return BAD_VALUE;
3038 }
3039 if (args.size() == 3 && args[0] == String16("set-uid-state")) {
3040 return handleSetUidState(args, err);
3041 } else if (args.size() == 2 && args[0] == String16("reset-uid-state")) {
3042 return handleResetUidState(args, err);
3043 } else if (args.size() == 2 && args[0] == String16("get-uid-state")) {
3044 return handleGetUidState(args, out, err);
3045 } else if (args.size() == 1 && args[0] == String16("help")) {
3046 printHelp(out);
3047 return NO_ERROR;
3048 }
3049 printHelp(err);
3050 return BAD_VALUE;
3051}
3052
3053status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
3054 PermissionController pc;
3055 int uid = pc.getPackageUid(args[1], 0);
3056 if (uid <= 0) {
3057 ALOGE("Unknown package: '%s'", String8(args[1]).string());
3058 dprintf(err, "Unknown package: '%s'\n", String8(args[1]).string());
3059 return BAD_VALUE;
3060 }
3061 bool active = false;
3062 if (args[2] == String16("active")) {
3063 active = true;
3064 } else if ((args[2] != String16("idle"))) {
3065 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
3066 return BAD_VALUE;
3067 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003068 mUidPolicy->addOverrideUid(uid, args[1], active);
Svet Ganova453d0d2018-01-11 15:37:58 -08003069 return NO_ERROR;
3070}
3071
3072status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
3073 PermissionController pc;
3074 int uid = pc.getPackageUid(args[1], 0);
3075 if (uid < 0) {
3076 ALOGE("Unknown package: '%s'", String8(args[1]).string());
3077 dprintf(err, "Unknown package: '%s'\n", String8(args[1]).string());
3078 return BAD_VALUE;
3079 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003080 mUidPolicy->removeOverrideUid(uid, args[1]);
Svet Ganova453d0d2018-01-11 15:37:58 -08003081 return NO_ERROR;
3082}
3083
3084status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
3085 PermissionController pc;
3086 int uid = pc.getPackageUid(args[1], 0);
3087 if (uid <= 0) {
3088 ALOGE("Unknown package: '%s'", String8(args[1]).string());
3089 dprintf(err, "Unknown package: '%s'\n", String8(args[1]).string());
3090 return BAD_VALUE;
3091 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003092 if (mUidPolicy->isUidActive(uid, args[1])) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003093 return dprintf(out, "active\n");
3094 } else {
3095 return dprintf(out, "idle\n");
3096 }
3097}
3098
3099status_t CameraService::printHelp(int out) {
3100 return dprintf(out, "Camera service commands:\n"
3101 " get-uid-state <PACKAGE> gets the uid state\n"
3102 " set-uid-state <PACKAGE> <active|idle> overrides the uid state\n"
3103 " reset-uid-state <PACKAGE> clears the uid state override\n"
3104 " help print this message\n");
3105}
3106
Mathias Agopian65ab4712010-07-14 17:59:35 -07003107}; // namespace android