1 /*
2  * 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  */
16 
17 #define LOG_TAG "CameraService"
18 #define ATRACE_TAG ATRACE_TAG_CAMERA
19 //#define LOG_NDEBUG 0
20 
21 #include <algorithm>
22 #include <climits>
23 #include <stdio.h>
24 #include <cstring>
25 #include <ctime>
26 #include <string>
27 #include <sys/types.h>
28 #include <inttypes.h>
29 #include <pthread.h>
30 
31 #include <android/hardware/ICamera.h>
32 #include <android/hardware/ICameraClient.h>
33 
34 #include <binder/AppOpsManager.h>
35 #include <binder/IPCThreadState.h>
36 #include <binder/IServiceManager.h>
37 #include <binder/MemoryBase.h>
38 #include <binder/MemoryHeapBase.h>
39 #include <binder/ProcessInfoService.h>
40 #include <cutils/atomic.h>
41 #include <cutils/properties.h>
42 #include <gui/Surface.h>
43 #include <hardware/hardware.h>
44 #include <memunreachable/memunreachable.h>
45 #include <media/AudioSystem.h>
46 #include <media/IMediaHTTPService.h>
47 #include <media/mediaplayer.h>
48 #include <mediautils/BatteryNotifier.h>
49 #include <utils/Errors.h>
50 #include <utils/Log.h>
51 #include <utils/String16.h>
52 #include <utils/Trace.h>
53 #include <private/android_filesystem_config.h>
54 #include <system/camera_vendor_tags.h>
55 #include <system/camera_metadata.h>
56 #include <system/camera.h>
57 
58 #include "CameraService.h"
59 #include "api1/CameraClient.h"
60 #include "api1/Camera2Client.h"
61 #include "api2/CameraDeviceClient.h"
62 #include "utils/CameraTraces.h"
63 
64 namespace {
65     const char* kPermissionServiceName = "permission";
66 }; // namespace anonymous
67 
68 namespace android {
69 
70 using binder::Status;
71 using namespace hardware;
72 
73 // ----------------------------------------------------------------------------
74 // Logging support -- this is for debugging only
75 // Use "adb shell dumpsys media.camera -v 1" to change it.
76 volatile int32_t gLogLevel = 0;
77 
78 #define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
79 #define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
80 
setLogLevel(int level)81 static void setLogLevel(int level) {
82     android_atomic_write(level, &gLogLevel);
83 }
84 
85 // Convenience methods for constructing binder::Status objects for error returns
86 
87 #define STATUS_ERROR(errorCode, errorString) \
88     binder::Status::fromServiceSpecificError(errorCode, \
89             String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
90 
91 #define STATUS_ERROR_FMT(errorCode, errorString, ...) \
92     binder::Status::fromServiceSpecificError(errorCode, \
93             String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, \
94                     __VA_ARGS__))
95 
96 // ----------------------------------------------------------------------------
97 
98 extern "C" {
camera_device_status_change(const struct camera_module_callbacks * callbacks,int camera_id,int new_status)99 static void camera_device_status_change(
100         const struct camera_module_callbacks* callbacks,
101         int camera_id,
102         int new_status) {
103     sp<CameraService> cs = const_cast<CameraService*>(
104             static_cast<const CameraService*>(callbacks));
105 
106     cs->onDeviceStatusChanged(static_cast<camera_device_status_t>(camera_id),
107             static_cast<camera_device_status_t>(new_status));
108 }
109 
torch_mode_status_change(const struct camera_module_callbacks * callbacks,const char * camera_id,int new_status)110 static void torch_mode_status_change(
111         const struct camera_module_callbacks* callbacks,
112         const char* camera_id,
113         int new_status) {
114     if (!callbacks || !camera_id) {
115         ALOGE("%s invalid parameters. callbacks %p, camera_id %p", __FUNCTION__,
116                 callbacks, camera_id);
117     }
118     sp<CameraService> cs = const_cast<CameraService*>(
119                                 static_cast<const CameraService*>(callbacks));
120 
121     int32_t status;
122     switch (new_status) {
123         case TORCH_MODE_STATUS_NOT_AVAILABLE:
124             status = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
125             break;
126         case TORCH_MODE_STATUS_AVAILABLE_OFF:
127             status = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
128             break;
129         case TORCH_MODE_STATUS_AVAILABLE_ON:
130             status = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
131             break;
132         default:
133             ALOGE("Unknown torch status %d", new_status);
134             return;
135     }
136 
137     cs->onTorchStatusChanged(
138         String8(camera_id),
139         status);
140 }
141 } // extern "C"
142 
143 // ----------------------------------------------------------------------------
144 
145 // This is ugly and only safe if we never re-create the CameraService, but
146 // should be ok for now.
147 static CameraService *gCameraService;
148 
CameraService()149 CameraService::CameraService() :
150         mEventLog(DEFAULT_EVENT_LOG_LENGTH),
151         mNumberOfCameras(0), mNumberOfNormalCameras(0),
152         mSoundRef(0), mModule(nullptr) {
153     ALOGI("CameraService started (pid=%d)", getpid());
154     gCameraService = this;
155 
156     this->camera_device_status_change = android::camera_device_status_change;
157     this->torch_mode_status_change = android::torch_mode_status_change;
158 
159     mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
160 }
161 
onFirstRef()162 void CameraService::onFirstRef()
163 {
164     ALOGI("CameraService process starting");
165 
166     BnCameraService::onFirstRef();
167 
168     // Update battery life tracking if service is restarting
169     BatteryNotifier& notifier(BatteryNotifier::getInstance());
170     notifier.noteResetCamera();
171     notifier.noteResetFlashlight();
172 
173     camera_module_t *rawModule;
174     int err = hw_get_module(CAMERA_HARDWARE_MODULE_ID,
175             (const hw_module_t **)&rawModule);
176     if (err < 0) {
177         ALOGE("Could not load camera HAL module: %d (%s)", err, strerror(-err));
178         logServiceError("Could not load camera HAL module", err);
179         return;
180     }
181 
182     mModule = new CameraModule(rawModule);
183     err = mModule->init();
184     if (err != OK) {
185         ALOGE("Could not initialize camera HAL module: %d (%s)", err,
186             strerror(-err));
187         logServiceError("Could not initialize camera HAL module", err);
188 
189         delete mModule;
190         mModule = nullptr;
191         return;
192     }
193     ALOGI("Loaded \"%s\" camera module", mModule->getModuleName());
194 
195     mNumberOfCameras = mModule->getNumberOfCameras();
196     mNumberOfNormalCameras = mNumberOfCameras;
197 
198     // Setup vendor tags before we call get_camera_info the first time
199     // because HAL might need to setup static vendor keys in get_camera_info
200     VendorTagDescriptor::clearGlobalVendorTagDescriptor();
201     if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_2) {
202         setUpVendorTags();
203     }
204 
205     mFlashlight = new CameraFlashlight(*mModule, *this);
206     status_t res = mFlashlight->findFlashUnits();
207     if (res) {
208         // impossible because we haven't open any camera devices.
209         ALOGE("Failed to find flash units.");
210     }
211 
212     int latestStrangeCameraId = INT_MAX;
213     for (int i = 0; i < mNumberOfCameras; i++) {
214         String8 cameraId = String8::format("%d", i);
215 
216         // Get camera info
217 
218         struct camera_info info;
219         bool haveInfo = true;
220         status_t rc = mModule->getCameraInfo(i, &info);
221         if (rc != NO_ERROR) {
222             ALOGE("%s: Received error loading camera info for device %d, cost and"
223                     " conflicting devices fields set to defaults for this device.",
224                     __FUNCTION__, i);
225             haveInfo = false;
226         }
227 
228         // Check for backwards-compatibility support
229         if (haveInfo) {
230             if (checkCameraCapabilities(i, info, &latestStrangeCameraId) != OK) {
231                 delete mModule;
232                 mModule = nullptr;
233                 return;
234             }
235         }
236 
237         // Defaults to use for cost and conflicting devices
238         int cost = 100;
239         char** conflicting_devices = nullptr;
240         size_t conflicting_devices_length = 0;
241 
242         // If using post-2.4 module version, query the cost + conflicting devices from the HAL
243         if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_4 && haveInfo) {
244             cost = info.resource_cost;
245             conflicting_devices = info.conflicting_devices;
246             conflicting_devices_length = info.conflicting_devices_length;
247         }
248 
249         std::set<String8> conflicting;
250         for (size_t i = 0; i < conflicting_devices_length; i++) {
251             conflicting.emplace(String8(conflicting_devices[i]));
252         }
253 
254         // Initialize state for each camera device
255         {
256             Mutex::Autolock lock(mCameraStatesLock);
257             mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost,
258                     conflicting));
259         }
260 
261         if (mFlashlight->hasFlashUnit(cameraId)) {
262             mTorchStatusMap.add(cameraId,
263                     ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF);
264         }
265     }
266 
267     if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_1) {
268         mModule->setCallbacks(this);
269     }
270 
271     CameraService::pingCameraServiceProxy();
272 }
273 
getCameraServiceProxy()274 sp<ICameraServiceProxy> CameraService::getCameraServiceProxy() {
275     sp<IServiceManager> sm = defaultServiceManager();
276     sp<IBinder> binder = sm->getService(String16("media.camera.proxy"));
277     if (binder == nullptr) {
278         return nullptr;
279     }
280     sp<ICameraServiceProxy> proxyBinder = interface_cast<ICameraServiceProxy>(binder);
281     return proxyBinder;
282 }
283 
pingCameraServiceProxy()284 void CameraService::pingCameraServiceProxy() {
285     sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
286     if (proxyBinder == nullptr) return;
287     proxyBinder->pingForUserUpdate();
288 }
289 
~CameraService()290 CameraService::~CameraService() {
291     if (mModule) {
292         delete mModule;
293         mModule = nullptr;
294     }
295     VendorTagDescriptor::clearGlobalVendorTagDescriptor();
296     gCameraService = nullptr;
297 }
298 
onDeviceStatusChanged(camera_device_status_t cameraId,camera_device_status_t newStatus)299 void CameraService::onDeviceStatusChanged(camera_device_status_t  cameraId,
300         camera_device_status_t newStatus) {
301     ALOGI("%s: Status changed for cameraId=%d, newStatus=%d", __FUNCTION__,
302           cameraId, newStatus);
303 
304     String8 id = String8::format("%d", cameraId);
305     std::shared_ptr<CameraState> state = getCameraState(id);
306 
307     if (state == nullptr) {
308         ALOGE("%s: Bad camera ID %d", __FUNCTION__, cameraId);
309         return;
310     }
311 
312     int32_t oldStatus = state->getStatus();
313 
314     if (oldStatus == static_cast<int32_t>(newStatus)) {
315         ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
316         return;
317     }
318 
319     if (newStatus == CAMERA_DEVICE_STATUS_NOT_PRESENT) {
320         logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
321                 newStatus));
322         sp<BasicClient> clientToDisconnect;
323         {
324             // Don't do this in updateStatus to avoid deadlock over mServiceLock
325             Mutex::Autolock lock(mServiceLock);
326 
327             // Set the device status to NOT_PRESENT, clients will no longer be able to connect
328             // to this device until the status changes
329             updateStatus(ICameraServiceListener::STATUS_NOT_PRESENT, id);
330 
331             // Remove cached shim parameters
332             state->setShimParams(CameraParameters());
333 
334             // Remove the client from the list of active clients
335             clientToDisconnect = removeClientLocked(id);
336 
337             // Notify the client of disconnection
338             clientToDisconnect->notifyError(
339                     hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
340                     CaptureResultExtras{});
341         }
342 
343         ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
344                 __FUNCTION__, id.string());
345 
346         // Disconnect client
347         if (clientToDisconnect.get() != nullptr) {
348             // Ensure not in binder RPC so client disconnect PID checks work correctly
349             LOG_ALWAYS_FATAL_IF(getCallingPid() != getpid(),
350                     "onDeviceStatusChanged must be called from the camera service process!");
351             clientToDisconnect->disconnect();
352         }
353 
354     } else {
355         if (oldStatus == ICameraServiceListener::STATUS_NOT_PRESENT) {
356             logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
357                     newStatus));
358         }
359         updateStatus(static_cast<int32_t>(newStatus), id);
360     }
361 
362 }
363 
onTorchStatusChanged(const String8 & cameraId,int32_t newStatus)364 void CameraService::onTorchStatusChanged(const String8& cameraId,
365         int32_t newStatus) {
366     Mutex::Autolock al(mTorchStatusMutex);
367     onTorchStatusChangedLocked(cameraId, newStatus);
368 }
369 
onTorchStatusChangedLocked(const String8 & cameraId,int32_t newStatus)370 void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
371         int32_t newStatus) {
372     ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
373             __FUNCTION__, cameraId.string(), newStatus);
374 
375     int32_t status;
376     status_t res = getTorchStatusLocked(cameraId, &status);
377     if (res) {
378         ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
379                 __FUNCTION__, cameraId.string(), strerror(-res), res);
380         return;
381     }
382     if (status == newStatus) {
383         return;
384     }
385 
386     res = setTorchStatusLocked(cameraId, newStatus);
387     if (res) {
388         ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
389                 (uint32_t)newStatus, strerror(-res), res);
390         return;
391     }
392 
393     {
394         // Update battery life logging for flashlight
395         Mutex::Autolock al(mTorchUidMapMutex);
396         auto iter = mTorchUidMap.find(cameraId);
397         if (iter != mTorchUidMap.end()) {
398             int oldUid = iter->second.second;
399             int newUid = iter->second.first;
400             BatteryNotifier& notifier(BatteryNotifier::getInstance());
401             if (oldUid != newUid) {
402                 // If the UID has changed, log the status and update current UID in mTorchUidMap
403                 if (status == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
404                     notifier.noteFlashlightOff(cameraId, oldUid);
405                 }
406                 if (newStatus == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
407                     notifier.noteFlashlightOn(cameraId, newUid);
408                 }
409                 iter->second.second = newUid;
410             } else {
411                 // If the UID has not changed, log the status
412                 if (newStatus == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
413                     notifier.noteFlashlightOn(cameraId, oldUid);
414                 } else {
415                     notifier.noteFlashlightOff(cameraId, oldUid);
416                 }
417             }
418         }
419     }
420 
421     {
422         Mutex::Autolock lock(mStatusListenerLock);
423         for (auto& i : mListenerList) {
424             i->onTorchStatusChanged(newStatus, String16{cameraId});
425         }
426     }
427 }
428 
getNumberOfCameras(int32_t type,int32_t * numCameras)429 Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
430     ATRACE_CALL();
431     switch (type) {
432         case CAMERA_TYPE_BACKWARD_COMPATIBLE:
433             *numCameras = mNumberOfNormalCameras;
434             break;
435         case CAMERA_TYPE_ALL:
436             *numCameras = mNumberOfCameras;
437             break;
438         default:
439             ALOGW("%s: Unknown camera type %d",
440                     __FUNCTION__, type);
441             return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
442                     "Unknown camera type %d", type);
443     }
444     return Status::ok();
445 }
446 
getCameraInfo(int cameraId,CameraInfo * cameraInfo)447 Status CameraService::getCameraInfo(int cameraId,
448         CameraInfo* cameraInfo) {
449     ATRACE_CALL();
450     if (!mModule) {
451         return STATUS_ERROR(ERROR_DISCONNECTED,
452                 "Camera subsystem is not available");
453     }
454 
455     if (cameraId < 0 || cameraId >= mNumberOfCameras) {
456         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
457                 "CameraId is not valid");
458     }
459 
460     struct camera_info info;
461     Status rc = filterGetInfoErrorCode(
462         mModule->getCameraInfo(cameraId, &info));
463 
464     if (rc.isOk()) {
465         cameraInfo->facing = info.facing;
466         cameraInfo->orientation = info.orientation;
467         // CameraInfo is for android.hardware.Camera which does not
468         // support external camera facing. The closest approximation would be
469         // front camera.
470         if (cameraInfo->orientation == CAMERA_FACING_EXTERNAL) {
471             cameraInfo->orientation = CAMERA_FACING_FRONT;
472         }
473     }
474     return rc;
475 }
476 
cameraIdToInt(const String8 & cameraId)477 int CameraService::cameraIdToInt(const String8& cameraId) {
478     errno = 0;
479     size_t pos = 0;
480     int ret = stoi(std::string{cameraId.string()}, &pos);
481     if (errno != 0 || pos != cameraId.size()) {
482         return -1;
483     }
484     return ret;
485 }
486 
generateShimMetadata(int cameraId,CameraMetadata * cameraInfo)487 Status CameraService::generateShimMetadata(int cameraId, /*out*/CameraMetadata* cameraInfo) {
488     ATRACE_CALL();
489 
490     Status ret = Status::ok();
491 
492     struct CameraInfo info;
493     if (!(ret = getCameraInfo(cameraId, &info)).isOk()) {
494         return ret;
495     }
496 
497     CameraMetadata shimInfo;
498     int32_t orientation = static_cast<int32_t>(info.orientation);
499     status_t rc;
500     if ((rc = shimInfo.update(ANDROID_SENSOR_ORIENTATION, &orientation, 1)) != OK) {
501         return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
502                 "Error updating metadata: %d (%s)", rc, strerror(-rc));
503     }
504 
505     uint8_t facing = (info.facing == CAMERA_FACING_FRONT) ?
506             ANDROID_LENS_FACING_FRONT : ANDROID_LENS_FACING_BACK;
507     if ((rc = shimInfo.update(ANDROID_LENS_FACING, &facing, 1)) != OK) {
508         return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
509                 "Error updating metadata: %d (%s)", rc, strerror(-rc));
510     }
511 
512     CameraParameters shimParams;
513     if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
514         // Error logged by callee
515         return ret;
516     }
517 
518     Vector<Size> sizes;
519     Vector<Size> jpegSizes;
520     Vector<int32_t> formats;
521     {
522         shimParams.getSupportedPreviewSizes(/*out*/sizes);
523         shimParams.getSupportedPreviewFormats(/*out*/formats);
524         shimParams.getSupportedPictureSizes(/*out*/jpegSizes);
525     }
526 
527     // Always include IMPLEMENTATION_DEFINED
528     formats.add(HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED);
529 
530     const size_t INTS_PER_CONFIG = 4;
531 
532     // Build available stream configurations metadata
533     size_t streamConfigSize = (sizes.size() * formats.size() + jpegSizes.size()) * INTS_PER_CONFIG;
534 
535     Vector<int32_t> streamConfigs;
536     streamConfigs.setCapacity(streamConfigSize);
537 
538     for (size_t i = 0; i < formats.size(); ++i) {
539         for (size_t j = 0; j < sizes.size(); ++j) {
540             streamConfigs.add(formats[i]);
541             streamConfigs.add(sizes[j].width);
542             streamConfigs.add(sizes[j].height);
543             streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
544         }
545     }
546 
547     for (size_t i = 0; i < jpegSizes.size(); ++i) {
548         streamConfigs.add(HAL_PIXEL_FORMAT_BLOB);
549         streamConfigs.add(jpegSizes[i].width);
550         streamConfigs.add(jpegSizes[i].height);
551         streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
552     }
553 
554     if ((rc = shimInfo.update(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS,
555             streamConfigs.array(), streamConfigSize)) != OK) {
556         return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
557                 "Error updating metadata: %d (%s)", rc, strerror(-rc));
558     }
559 
560     int64_t fakeMinFrames[0];
561     // TODO: Fixme, don't fake min frame durations.
562     if ((rc = shimInfo.update(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS,
563             fakeMinFrames, 0)) != OK) {
564         return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
565                 "Error updating metadata: %d (%s)", rc, strerror(-rc));
566     }
567 
568     int64_t fakeStalls[0];
569     // TODO: Fixme, don't fake stall durations.
570     if ((rc = shimInfo.update(ANDROID_SCALER_AVAILABLE_STALL_DURATIONS,
571             fakeStalls, 0)) != OK) {
572         return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
573                 "Error updating metadata: %d (%s)", rc, strerror(-rc));
574     }
575 
576     *cameraInfo = shimInfo;
577     return ret;
578 }
579 
getCameraCharacteristics(int cameraId,CameraMetadata * cameraInfo)580 Status CameraService::getCameraCharacteristics(int cameraId,
581                                                 CameraMetadata* cameraInfo) {
582     ATRACE_CALL();
583     if (!cameraInfo) {
584         ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
585         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
586     }
587 
588     if (!mModule) {
589         ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
590         return STATUS_ERROR(ERROR_DISCONNECTED,
591                 "Camera subsystem is not available");;
592     }
593 
594     if (cameraId < 0 || cameraId >= mNumberOfCameras) {
595         ALOGE("%s: Invalid camera id: %d", __FUNCTION__, cameraId);
596         return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
597                 "Invalid camera id: %d", cameraId);
598     }
599 
600     int facing;
601     Status ret;
602     if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0 ||
603             getDeviceVersion(cameraId, &facing) < CAMERA_DEVICE_API_VERSION_3_0) {
604         /**
605          * Backwards compatibility mode for old HALs:
606          * - Convert CameraInfo into static CameraMetadata properties.
607          * - Retrieve cached CameraParameters for this camera.  If none exist,
608          *   attempt to open CameraClient and retrieve the CameraParameters.
609          * - Convert cached CameraParameters into static CameraMetadata
610          *   properties.
611          */
612         ALOGI("%s: Switching to HAL1 shim implementation...", __FUNCTION__);
613 
614         ret = generateShimMetadata(cameraId, cameraInfo);
615     } else {
616         /**
617          * Normal HAL 2.1+ codepath.
618          */
619         struct camera_info info;
620         ret = filterGetInfoErrorCode(mModule->getCameraInfo(cameraId, &info));
621         if (ret.isOk()) {
622             *cameraInfo = info.static_camera_characteristics;
623         }
624     }
625 
626     return ret;
627 }
628 
getCallingPid()629 int CameraService::getCallingPid() {
630     return IPCThreadState::self()->getCallingPid();
631 }
632 
getCallingUid()633 int CameraService::getCallingUid() {
634     return IPCThreadState::self()->getCallingUid();
635 }
636 
getFormattedCurrentTime()637 String8 CameraService::getFormattedCurrentTime() {
638     time_t now = time(nullptr);
639     char formattedTime[64];
640     strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
641     return String8(formattedTime);
642 }
643 
getCameraPriorityFromProcState(int procState)644 int CameraService::getCameraPriorityFromProcState(int procState) {
645     // Find the priority for the camera usage based on the process state.  Higher priority clients
646     // win for evictions.
647     if (procState < 0) {
648         ALOGE("%s: Received invalid process state %d from ActivityManagerService!", __FUNCTION__,
649                 procState);
650         return -1;
651     }
652     // Treat sleeping TOP processes the same as regular TOP processes, for
653     // access priority.  This is important for lock-screen camera launch scenarios
654     if (procState == PROCESS_STATE_TOP_SLEEPING) {
655         procState = PROCESS_STATE_TOP;
656     }
657     return INT_MAX - procState;
658 }
659 
getCameraVendorTagDescriptor(hardware::camera2::params::VendorTagDescriptor * desc)660 Status CameraService::getCameraVendorTagDescriptor(
661         /*out*/
662         hardware::camera2::params::VendorTagDescriptor* desc) {
663     ATRACE_CALL();
664     if (!mModule) {
665         ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
666         return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
667     }
668     sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
669     if (globalDescriptor != nullptr) {
670         *desc = *(globalDescriptor.get());
671     }
672     return Status::ok();
673 }
674 
getDeviceVersion(int cameraId,int * facing)675 int CameraService::getDeviceVersion(int cameraId, int* facing) {
676     ATRACE_CALL();
677     struct camera_info info;
678     if (mModule->getCameraInfo(cameraId, &info) != OK) {
679         return -1;
680     }
681 
682     int deviceVersion;
683     if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0) {
684         deviceVersion = info.device_version;
685     } else {
686         deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
687     }
688 
689     if (facing) {
690         *facing = info.facing;
691     }
692 
693     return deviceVersion;
694 }
695 
filterGetInfoErrorCode(status_t err)696 Status CameraService::filterGetInfoErrorCode(status_t err) {
697     switch(err) {
698         case NO_ERROR:
699             return Status::ok();
700         case -EINVAL:
701             return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
702                     "CameraId is not valid for HAL module");
703         case -ENODEV:
704             return STATUS_ERROR(ERROR_DISCONNECTED,
705                     "Camera device not available");
706         default:
707             return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
708                     "Camera HAL encountered error %d: %s",
709                     err, strerror(-err));
710     }
711 }
712 
setUpVendorTags()713 bool CameraService::setUpVendorTags() {
714     ATRACE_CALL();
715     vendor_tag_ops_t vOps = vendor_tag_ops_t();
716 
717     // Check if vendor operations have been implemented
718     if (!mModule->isVendorTagDefined()) {
719         ALOGI("%s: No vendor tags defined for this device.", __FUNCTION__);
720         return false;
721     }
722 
723     mModule->getVendorTagOps(&vOps);
724 
725     // Ensure all vendor operations are present
726     if (vOps.get_tag_count == NULL || vOps.get_all_tags == NULL ||
727             vOps.get_section_name == NULL || vOps.get_tag_name == NULL ||
728             vOps.get_tag_type == NULL) {
729         ALOGE("%s: Vendor tag operations not fully defined. Ignoring definitions."
730                , __FUNCTION__);
731         return false;
732     }
733 
734     // Read all vendor tag definitions into a descriptor
735     sp<VendorTagDescriptor> desc;
736     status_t res;
737     if ((res = VendorTagDescriptor::createDescriptorFromOps(&vOps, /*out*/desc))
738             != OK) {
739         ALOGE("%s: Could not generate descriptor from vendor tag operations,"
740               "received error %s (%d). Camera clients will not be able to use"
741               "vendor tags", __FUNCTION__, strerror(res), res);
742         return false;
743     }
744 
745     // Set the global descriptor to use with camera metadata
746     VendorTagDescriptor::setAsGlobalVendorTagDescriptor(desc);
747     return true;
748 }
749 
makeClient(const sp<CameraService> & cameraService,const sp<IInterface> & cameraCb,const String16 & packageName,int cameraId,int facing,int clientPid,uid_t clientUid,int servicePid,bool legacyMode,int halVersion,int deviceVersion,apiLevel effectiveApiLevel,sp<BasicClient> * client)750 Status CameraService::makeClient(const sp<CameraService>& cameraService,
751         const sp<IInterface>& cameraCb, const String16& packageName, int cameraId,
752         int facing, int clientPid, uid_t clientUid, int servicePid, bool legacyMode,
753         int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
754         /*out*/sp<BasicClient>* client) {
755 
756     if (halVersion < 0 || halVersion == deviceVersion) {
757         // Default path: HAL version is unspecified by caller, create CameraClient
758         // based on device version reported by the HAL.
759         switch(deviceVersion) {
760           case CAMERA_DEVICE_API_VERSION_1_0:
761             if (effectiveApiLevel == API_1) {  // Camera1 API route
762                 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
763                 *client = new CameraClient(cameraService, tmp, packageName, cameraId, facing,
764                         clientPid, clientUid, getpid(), legacyMode);
765             } else { // Camera2 API route
766                 ALOGW("Camera using old HAL version: %d", deviceVersion);
767                 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
768                         "Camera device \"%d\" HAL version %d does not support camera2 API",
769                         cameraId, deviceVersion);
770             }
771             break;
772           case CAMERA_DEVICE_API_VERSION_3_0:
773           case CAMERA_DEVICE_API_VERSION_3_1:
774           case CAMERA_DEVICE_API_VERSION_3_2:
775           case CAMERA_DEVICE_API_VERSION_3_3:
776           case CAMERA_DEVICE_API_VERSION_3_4:
777             if (effectiveApiLevel == API_1) { // Camera1 API route
778                 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
779                 *client = new Camera2Client(cameraService, tmp, packageName, cameraId, facing,
780                         clientPid, clientUid, servicePid, legacyMode);
781             } else { // Camera2 API route
782                 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
783                         static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
784                 *client = new CameraDeviceClient(cameraService, tmp, packageName, cameraId,
785                         facing, clientPid, clientUid, servicePid);
786             }
787             break;
788           default:
789             // Should not be reachable
790             ALOGE("Unknown camera device HAL version: %d", deviceVersion);
791             return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
792                     "Camera device \"%d\" has unknown HAL version %d",
793                     cameraId, deviceVersion);
794         }
795     } else {
796         // A particular HAL version is requested by caller. Create CameraClient
797         // based on the requested HAL version.
798         if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
799             halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
800             // Only support higher HAL version device opened as HAL1.0 device.
801             sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
802             *client = new CameraClient(cameraService, tmp, packageName, cameraId, facing,
803                     clientPid, clientUid, servicePid, legacyMode);
804         } else {
805             // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
806             ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
807                     " opened as HAL %x device", halVersion, deviceVersion,
808                     CAMERA_DEVICE_API_VERSION_1_0);
809             return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
810                     "Camera device \"%d\" (HAL version %d) cannot be opened as HAL version %d",
811                     cameraId, deviceVersion, halVersion);
812         }
813     }
814     return Status::ok();
815 }
816 
toString(std::set<userid_t> intSet)817 String8 CameraService::toString(std::set<userid_t> intSet) {
818     String8 s("");
819     bool first = true;
820     for (userid_t i : intSet) {
821         if (first) {
822             s.appendFormat("%d", i);
823             first = false;
824         } else {
825             s.appendFormat(", %d", i);
826         }
827     }
828     return s;
829 }
830 
initializeShimMetadata(int cameraId)831 Status CameraService::initializeShimMetadata(int cameraId) {
832     int uid = getCallingUid();
833 
834     String16 internalPackageName("cameraserver");
835     String8 id = String8::format("%d", cameraId);
836     Status ret = Status::ok();
837     sp<Client> tmp = nullptr;
838     if (!(ret = connectHelper<ICameraClient,Client>(
839             sp<ICameraClient>{nullptr}, id, static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED),
840             internalPackageName, uid, USE_CALLING_PID,
841             API_1, /*legacyMode*/ false, /*shimUpdateOnly*/ true,
842             /*out*/ tmp)
843             ).isOk()) {
844         ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
845     }
846     return ret;
847 }
848 
getLegacyParametersLazy(int cameraId,CameraParameters * parameters)849 Status CameraService::getLegacyParametersLazy(int cameraId,
850         /*out*/
851         CameraParameters* parameters) {
852 
853     ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
854 
855     Status ret = Status::ok();
856 
857     if (parameters == NULL) {
858         ALOGE("%s: parameters must not be null", __FUNCTION__);
859         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
860     }
861 
862     String8 id = String8::format("%d", cameraId);
863 
864     // Check if we already have parameters
865     {
866         // Scope for service lock
867         Mutex::Autolock lock(mServiceLock);
868         auto cameraState = getCameraState(id);
869         if (cameraState == nullptr) {
870             ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
871             return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
872                     "Invalid camera ID: %s", id.string());
873         }
874         CameraParameters p = cameraState->getShimParams();
875         if (!p.isEmpty()) {
876             *parameters = p;
877             return ret;
878         }
879     }
880 
881     int64_t token = IPCThreadState::self()->clearCallingIdentity();
882     ret = initializeShimMetadata(cameraId);
883     IPCThreadState::self()->restoreCallingIdentity(token);
884     if (!ret.isOk()) {
885         // Error already logged by callee
886         return ret;
887     }
888 
889     // Check for parameters again
890     {
891         // Scope for service lock
892         Mutex::Autolock lock(mServiceLock);
893         auto cameraState = getCameraState(id);
894         if (cameraState == nullptr) {
895             ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
896             return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
897                     "Invalid camera ID: %s", id.string());
898         }
899         CameraParameters p = cameraState->getShimParams();
900         if (!p.isEmpty()) {
901             *parameters = p;
902             return ret;
903         }
904     }
905 
906     ALOGE("%s: Parameters were not initialized, or were empty.  Device may not be present.",
907             __FUNCTION__);
908     return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
909 }
910 
911 // Can camera service trust the caller based on the calling UID?
isTrustedCallingUid(uid_t uid)912 static bool isTrustedCallingUid(uid_t uid) {
913     switch (uid) {
914         case AID_MEDIA:         // mediaserver
915         case AID_CAMERASERVER: // cameraserver
916             return true;
917         default:
918             return false;
919     }
920 }
921 
validateConnectLocked(const String8 & cameraId,const String8 & clientName8,int & clientUid,int & clientPid,int & originalClientPid) const922 Status CameraService::validateConnectLocked(const String8& cameraId,
923         const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
924         /*out*/int& originalClientPid) const {
925 
926     int callingPid = getCallingPid();
927     int callingUid = getCallingUid();
928 
929     // Check if we can trust clientUid
930     if (clientUid == USE_CALLING_UID) {
931         clientUid = callingUid;
932     } else if (!isTrustedCallingUid(callingUid)) {
933         ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
934                 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
935         return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
936                 "Untrusted caller (calling PID %d, UID %d) trying to "
937                 "forward camera access to camera %s for client %s (PID %d, UID %d)",
938                 callingPid, callingUid, cameraId.string(),
939                 clientName8.string(), clientUid, clientPid);
940     }
941 
942     // Check if we can trust clientPid
943     if (clientPid == USE_CALLING_PID) {
944         clientPid = callingPid;
945     } else if (!isTrustedCallingUid(callingUid)) {
946         ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
947                 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
948         return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
949                 "Untrusted caller (calling PID %d, UID %d) trying to "
950                 "forward camera access to camera %s for client %s (PID %d, UID %d)",
951                 callingPid, callingUid, cameraId.string(),
952                 clientName8.string(), clientUid, clientPid);
953     }
954 
955     // If it's not calling from cameraserver, check the permission.
956     if (callingPid != getpid() &&
957             !checkPermission(String16("android.permission.CAMERA"), clientPid, clientUid)) {
958         ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
959         return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
960                 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
961                 clientName8.string(), clientUid, clientPid, cameraId.string());
962     }
963 
964     // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
965     // connected to camera service directly.
966     originalClientPid = clientPid;
967     clientPid = callingPid;
968 
969     if (!mModule) {
970         ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
971                 callingPid);
972         return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
973                 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
974     }
975 
976     if (getCameraState(cameraId) == nullptr) {
977         ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
978                 cameraId.string());
979         return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
980                 "No camera device with ID \"%s\" available", cameraId.string());
981     }
982 
983     userid_t clientUserId = multiuser_get_user_id(clientUid);
984 
985     // Only allow clients who are being used by the current foreground device user, unless calling
986     // from our own process.
987     if (callingPid != getpid() && (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
988         ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
989                 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
990                 toString(mAllowedUsers).string());
991         return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
992                 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
993                 clientUserId, cameraId.string());
994     }
995 
996     status_t err = checkIfDeviceIsUsable(cameraId);
997     if (err != NO_ERROR) {
998         switch(err) {
999             case -ENODEV:
1000             case -EBUSY:
1001                 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1002                         "No camera device with ID \"%s\" currently available", cameraId.string());
1003             default:
1004                 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1005                         "Unknown error connecting to ID \"%s\"", cameraId.string());
1006         }
1007     }
1008     return Status::ok();
1009 }
1010 
checkIfDeviceIsUsable(const String8 & cameraId) const1011 status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1012     auto cameraState = getCameraState(cameraId);
1013     int callingPid = getCallingPid();
1014     if (cameraState == nullptr) {
1015         ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1016                 cameraId.string());
1017         return -ENODEV;
1018     }
1019 
1020     int32_t currentStatus = cameraState->getStatus();
1021     if (currentStatus == ICameraServiceListener::STATUS_NOT_PRESENT) {
1022         ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1023                 callingPid, cameraId.string());
1024         return -ENODEV;
1025     } else if (currentStatus == ICameraServiceListener::STATUS_ENUMERATING) {
1026         ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1027                 callingPid, cameraId.string());
1028         return -EBUSY;
1029     }
1030 
1031     return NO_ERROR;
1032 }
1033 
finishConnectLocked(const sp<BasicClient> & client,const CameraService::DescriptorPtr & desc)1034 void CameraService::finishConnectLocked(const sp<BasicClient>& client,
1035         const CameraService::DescriptorPtr& desc) {
1036 
1037     // Make a descriptor for the incoming client
1038     auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
1039     auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1040 
1041     logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1042             String8(client->getPackageName()));
1043 
1044     if (evicted.size() > 0) {
1045         // This should never happen - clients should already have been removed in disconnect
1046         for (auto& i : evicted) {
1047             ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1048                     __FUNCTION__, i->getKey().string());
1049         }
1050 
1051         LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1052                 __FUNCTION__);
1053     }
1054 
1055     // And register a death notification for the client callback. Do
1056     // this last to avoid Binder policy where a nested Binder
1057     // transaction might be pre-empted to service the client death
1058     // notification if the client process dies before linkToDeath is
1059     // invoked.
1060     sp<IBinder> remoteCallback = client->getRemote();
1061     if (remoteCallback != nullptr) {
1062         remoteCallback->linkToDeath(this);
1063     }
1064 }
1065 
handleEvictionsLocked(const String8 & cameraId,int clientPid,apiLevel effectiveApiLevel,const sp<IBinder> & remoteCallback,const String8 & packageName,sp<BasicClient> * client,std::shared_ptr<resource_policy::ClientDescriptor<String8,sp<BasicClient>>> * partial)1066 status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1067         apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
1068         /*out*/
1069         sp<BasicClient>* client,
1070         std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
1071     ATRACE_CALL();
1072     status_t ret = NO_ERROR;
1073     std::vector<DescriptorPtr> evictedClients;
1074     DescriptorPtr clientDescriptor;
1075     {
1076         if (effectiveApiLevel == API_1) {
1077             // If we are using API1, any existing client for this camera ID with the same remote
1078             // should be returned rather than evicted to allow MediaRecorder to work properly.
1079 
1080             auto current = mActiveClientManager.get(cameraId);
1081             if (current != nullptr) {
1082                 auto clientSp = current->getValue();
1083                 if (clientSp.get() != nullptr) { // should never be needed
1084                     if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1085                         ALOGW("CameraService connect called from same client, but with a different"
1086                                 " API level, evicting prior client...");
1087                     } else if (clientSp->getRemote() == remoteCallback) {
1088                         ALOGI("CameraService::connect X (PID %d) (second call from same"
1089                                 " app binder, returning the same client)", clientPid);
1090                         *client = clientSp;
1091                         return NO_ERROR;
1092                     }
1093                 }
1094             }
1095         }
1096 
1097         // Get current active client PIDs
1098         std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1099         ownerPids.push_back(clientPid);
1100 
1101         // Use the value +PROCESS_STATE_NONEXISTENT, to avoid taking
1102         // address of PROCESS_STATE_NONEXISTENT as a reference argument
1103         // for the vector constructor. PROCESS_STATE_NONEXISTENT does
1104         // not have an out-of-class definition.
1105         std::vector<int> priorities(ownerPids.size(), +PROCESS_STATE_NONEXISTENT);
1106 
1107         // Get priorites of all active PIDs
1108         ProcessInfoService::getProcessStatesFromPids(ownerPids.size(), &ownerPids[0],
1109                 /*out*/&priorities[0]);
1110 
1111         // Update all active clients' priorities
1112         std::map<int,int> pidToPriorityMap;
1113         for (size_t i = 0; i < ownerPids.size() - 1; i++) {
1114             pidToPriorityMap.emplace(ownerPids[i], getCameraPriorityFromProcState(priorities[i]));
1115         }
1116         mActiveClientManager.updatePriorities(pidToPriorityMap);
1117 
1118         // Get state for the given cameraId
1119         auto state = getCameraState(cameraId);
1120         if (state == nullptr) {
1121             ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1122                 clientPid, cameraId.string());
1123             // Should never get here because validateConnectLocked should have errored out
1124             return BAD_VALUE;
1125         }
1126 
1127         // Make descriptor for incoming client
1128         clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1129                 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1130                 state->getConflicting(),
1131                 getCameraPriorityFromProcState(priorities[priorities.size() - 1]), clientPid);
1132 
1133         // Find clients that would be evicted
1134         auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1135 
1136         // If the incoming client was 'evicted,' higher priority clients have the camera in the
1137         // background, so we cannot do evictions
1138         if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1139             ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1140                     " priority).", clientPid);
1141 
1142             sp<BasicClient> clientSp = clientDescriptor->getValue();
1143             String8 curTime = getFormattedCurrentTime();
1144             auto incompatibleClients =
1145                     mActiveClientManager.getIncompatibleClients(clientDescriptor);
1146 
1147             String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
1148                     "(PID %d, priority %d) due to eviction policy", curTime.string(),
1149                     cameraId.string(), packageName.string(), clientPid,
1150                     getCameraPriorityFromProcState(priorities[priorities.size() - 1]));
1151 
1152             for (auto& i : incompatibleClients) {
1153                 msg.appendFormat("\n   - Blocked by existing device %s client for package %s"
1154                         "(PID %" PRId32 ", priority %" PRId32 ")", i->getKey().string(),
1155                         String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
1156                         i->getPriority());
1157                 ALOGE("   Conflicts with: Device %s, client package %s (PID %"
1158                         PRId32 ", priority %" PRId32 ")", i->getKey().string(),
1159                         String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
1160                         i->getPriority());
1161             }
1162 
1163             // Log the client's attempt
1164             Mutex::Autolock l(mLogLock);
1165             mEventLog.add(msg);
1166 
1167             return -EBUSY;
1168         }
1169 
1170         for (auto& i : evicted) {
1171             sp<BasicClient> clientSp = i->getValue();
1172             if (clientSp.get() == nullptr) {
1173                 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1174 
1175                 // TODO: Remove this
1176                 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1177                         __FUNCTION__);
1178                 mActiveClientManager.remove(i);
1179                 continue;
1180             }
1181 
1182             ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1183                     i->getKey().string());
1184             evictedClients.push_back(i);
1185 
1186             // Log the clients evicted
1187             logEvent(String8::format("EVICT device %s client held by package %s (PID"
1188                     " %" PRId32 ", priority %" PRId32 ")\n   - Evicted by device %s client for"
1189                     " package %s (PID %d, priority %" PRId32 ")",
1190                     i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1191                     i->getOwnerId(), i->getPriority(), cameraId.string(),
1192                     packageName.string(), clientPid,
1193                     getCameraPriorityFromProcState(priorities[priorities.size() - 1])));
1194 
1195             // Notify the client of disconnection
1196             clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1197                     CaptureResultExtras());
1198         }
1199     }
1200 
1201     // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1202     // other clients from connecting in mServiceLockWrapper if held
1203     mServiceLock.unlock();
1204 
1205     // Clear caller identity temporarily so client disconnect PID checks work correctly
1206     int64_t token = IPCThreadState::self()->clearCallingIdentity();
1207 
1208     // Destroy evicted clients
1209     for (auto& i : evictedClients) {
1210         // Disconnect is blocking, and should only have returned when HAL has cleaned up
1211         i->getValue()->disconnect(); // Clients will remove themselves from the active client list
1212     }
1213 
1214     IPCThreadState::self()->restoreCallingIdentity(token);
1215 
1216     for (const auto& i : evictedClients) {
1217         ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1218                 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1219         ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1220         if (ret == TIMED_OUT) {
1221             ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1222                     "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1223                     mActiveClientManager.toString().string());
1224             return -EBUSY;
1225         }
1226         if (ret != NO_ERROR) {
1227             ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1228                     "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1229                     ret, mActiveClientManager.toString().string());
1230             return ret;
1231         }
1232     }
1233 
1234     evictedClients.clear();
1235 
1236     // Once clients have been disconnected, relock
1237     mServiceLock.lock();
1238 
1239     // Check again if the device was unplugged or something while we weren't holding mServiceLock
1240     if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1241         return ret;
1242     }
1243 
1244     *partial = clientDescriptor;
1245     return NO_ERROR;
1246 }
1247 
connect(const sp<ICameraClient> & cameraClient,int cameraId,const String16 & clientPackageName,int clientUid,int clientPid,sp<ICamera> * device)1248 Status CameraService::connect(
1249         const sp<ICameraClient>& cameraClient,
1250         int cameraId,
1251         const String16& clientPackageName,
1252         int clientUid,
1253         int clientPid,
1254         /*out*/
1255         sp<ICamera>* device) {
1256 
1257     ATRACE_CALL();
1258     Status ret = Status::ok();
1259     String8 id = String8::format("%d", cameraId);
1260     sp<Client> client = nullptr;
1261     ret = connectHelper<ICameraClient,Client>(cameraClient, id,
1262             CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, clientUid, clientPid, API_1,
1263             /*legacyMode*/ false, /*shimUpdateOnly*/ false,
1264             /*out*/client);
1265 
1266     if(!ret.isOk()) {
1267         logRejected(id, getCallingPid(), String8(clientPackageName),
1268                 ret.toString8());
1269         return ret;
1270     }
1271 
1272     *device = client;
1273     return ret;
1274 }
1275 
connectLegacy(const sp<ICameraClient> & cameraClient,int cameraId,int halVersion,const String16 & clientPackageName,int clientUid,sp<ICamera> * device)1276 Status CameraService::connectLegacy(
1277         const sp<ICameraClient>& cameraClient,
1278         int cameraId, int halVersion,
1279         const String16& clientPackageName,
1280         int clientUid,
1281         /*out*/
1282         sp<ICamera>* device) {
1283 
1284     ATRACE_CALL();
1285     String8 id = String8::format("%d", cameraId);
1286     int apiVersion = mModule->getModuleApiVersion();
1287     if (halVersion != CAMERA_HAL_API_VERSION_UNSPECIFIED &&
1288             apiVersion < CAMERA_MODULE_API_VERSION_2_3) {
1289         /*
1290          * Either the HAL version is unspecified in which case this just creates
1291          * a camera client selected by the latest device version, or
1292          * it's a particular version in which case the HAL must supported
1293          * the open_legacy call
1294          */
1295         String8 msg = String8::format("Camera HAL module version %x too old for connectLegacy!",
1296                 apiVersion);
1297         ALOGE("%s: %s",
1298                 __FUNCTION__, msg.string());
1299         logRejected(id, getCallingPid(), String8(clientPackageName),
1300                 msg);
1301         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
1302     }
1303 
1304     Status ret = Status::ok();
1305     sp<Client> client = nullptr;
1306     ret = connectHelper<ICameraClient,Client>(cameraClient, id, halVersion,
1307             clientPackageName, clientUid, USE_CALLING_PID, API_1,
1308             /*legacyMode*/ true, /*shimUpdateOnly*/ false,
1309             /*out*/client);
1310 
1311     if(!ret.isOk()) {
1312         logRejected(id, getCallingPid(), String8(clientPackageName),
1313                 ret.toString8());
1314         return ret;
1315     }
1316 
1317     *device = client;
1318     return ret;
1319 }
1320 
connectDevice(const sp<hardware::camera2::ICameraDeviceCallbacks> & cameraCb,int cameraId,const String16 & clientPackageName,int clientUid,sp<hardware::camera2::ICameraDeviceUser> * device)1321 Status CameraService::connectDevice(
1322         const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
1323         int cameraId,
1324         const String16& clientPackageName,
1325         int clientUid,
1326         /*out*/
1327         sp<hardware::camera2::ICameraDeviceUser>* device) {
1328 
1329     ATRACE_CALL();
1330     Status ret = Status::ok();
1331     String8 id = String8::format("%d", cameraId);
1332     sp<CameraDeviceClient> client = nullptr;
1333     ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
1334             CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName,
1335             clientUid, USE_CALLING_PID, API_2,
1336             /*legacyMode*/ false, /*shimUpdateOnly*/ false,
1337             /*out*/client);
1338 
1339     if(!ret.isOk()) {
1340         logRejected(id, getCallingPid(), String8(clientPackageName),
1341                 ret.toString8());
1342         return ret;
1343     }
1344 
1345     *device = client;
1346     return ret;
1347 }
1348 
setTorchMode(const String16 & cameraId,bool enabled,const sp<IBinder> & clientBinder)1349 Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
1350         const sp<IBinder>& clientBinder) {
1351 
1352     ATRACE_CALL();
1353     if (enabled && clientBinder == nullptr) {
1354         ALOGE("%s: torch client binder is NULL", __FUNCTION__);
1355         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1356                 "Torch client Binder is null");
1357     }
1358 
1359     String8 id = String8(cameraId.string());
1360     int uid = getCallingUid();
1361 
1362     // verify id is valid.
1363     auto state = getCameraState(id);
1364     if (state == nullptr) {
1365         ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
1366         return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1367                 "Camera ID \"%s\" is a not valid camera ID", id.string());
1368     }
1369 
1370     int32_t cameraStatus = state->getStatus();
1371     if (cameraStatus != ICameraServiceListener::STATUS_PRESENT &&
1372             cameraStatus != ICameraServiceListener::STATUS_NOT_AVAILABLE) {
1373         ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
1374         return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1375                 "Camera ID \"%s\" is a not valid camera ID", id.string());
1376     }
1377 
1378     {
1379         Mutex::Autolock al(mTorchStatusMutex);
1380         int32_t status;
1381         status_t err = getTorchStatusLocked(id, &status);
1382         if (err != OK) {
1383             if (err == NAME_NOT_FOUND) {
1384                 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1385                         "Camera \"%s\" does not have a flash unit", id.string());
1386             }
1387             ALOGE("%s: getting current torch status failed for camera %s",
1388                     __FUNCTION__, id.string());
1389             return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1390                     "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
1391                     strerror(-err), err);
1392         }
1393 
1394         if (status == ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE) {
1395             if (cameraStatus == ICameraServiceListener::STATUS_NOT_AVAILABLE) {
1396                 ALOGE("%s: torch mode of camera %s is not available because "
1397                         "camera is in use", __FUNCTION__, id.string());
1398                 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1399                         "Torch for camera \"%s\" is not available due to an existing camera user",
1400                         id.string());
1401             } else {
1402                 ALOGE("%s: torch mode of camera %s is not available due to "
1403                         "insufficient resources", __FUNCTION__, id.string());
1404                 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1405                         "Torch for camera \"%s\" is not available due to insufficient resources",
1406                         id.string());
1407             }
1408         }
1409     }
1410 
1411     {
1412         // Update UID map - this is used in the torch status changed callbacks, so must be done
1413         // before setTorchMode
1414         Mutex::Autolock al(mTorchUidMapMutex);
1415         if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1416             mTorchUidMap[id].first = uid;
1417             mTorchUidMap[id].second = uid;
1418         } else {
1419             // Set the pending UID
1420             mTorchUidMap[id].first = uid;
1421         }
1422     }
1423 
1424     status_t err = mFlashlight->setTorchMode(id, enabled);
1425 
1426     if (err != OK) {
1427         int32_t errorCode;
1428         String8 msg;
1429         switch (err) {
1430             case -ENOSYS:
1431                 msg = String8::format("Camera \"%s\" has no flashlight",
1432                     id.string());
1433                 errorCode = ERROR_ILLEGAL_ARGUMENT;
1434                 break;
1435             default:
1436                 msg = String8::format(
1437                     "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1438                     id.string(), enabled, strerror(-err), err);
1439                 errorCode = ERROR_INVALID_OPERATION;
1440         }
1441         ALOGE("%s: %s", __FUNCTION__, msg.string());
1442         return STATUS_ERROR(errorCode, msg.string());
1443     }
1444 
1445     {
1446         // update the link to client's death
1447         Mutex::Autolock al(mTorchClientMapMutex);
1448         ssize_t index = mTorchClientMap.indexOfKey(id);
1449         if (enabled) {
1450             if (index == NAME_NOT_FOUND) {
1451                 mTorchClientMap.add(id, clientBinder);
1452             } else {
1453                 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
1454                 mTorchClientMap.replaceValueAt(index, clientBinder);
1455             }
1456             clientBinder->linkToDeath(this);
1457         } else if (index != NAME_NOT_FOUND) {
1458             mTorchClientMap.valueAt(index)->unlinkToDeath(this);
1459         }
1460     }
1461 
1462     return Status::ok();
1463 }
1464 
notifySystemEvent(int32_t eventId,const std::vector<int32_t> & args)1465 Status CameraService::notifySystemEvent(int32_t eventId,
1466         const std::vector<int32_t>& args) {
1467     ATRACE_CALL();
1468 
1469     switch(eventId) {
1470         case ICameraService::EVENT_USER_SWITCHED: {
1471             doUserSwitch(/*newUserIds*/ args);
1472             break;
1473         }
1474         case ICameraService::EVENT_NONE:
1475         default: {
1476             ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1477                     eventId);
1478             break;
1479         }
1480     }
1481     return Status::ok();
1482 }
1483 
addListener(const sp<ICameraServiceListener> & listener)1484 Status CameraService::addListener(const sp<ICameraServiceListener>& listener) {
1485     ATRACE_CALL();
1486 
1487     ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
1488 
1489     if (listener == nullptr) {
1490         ALOGE("%s: Listener must not be null", __FUNCTION__);
1491         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
1492     }
1493 
1494     Mutex::Autolock lock(mServiceLock);
1495 
1496     {
1497         Mutex::Autolock lock(mStatusListenerLock);
1498         for (auto& it : mListenerList) {
1499             if (IInterface::asBinder(it) == IInterface::asBinder(listener)) {
1500                 ALOGW("%s: Tried to add listener %p which was already subscribed",
1501                       __FUNCTION__, listener.get());
1502                 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
1503             }
1504         }
1505 
1506         mListenerList.push_back(listener);
1507     }
1508 
1509 
1510     /* Immediately signal current status to this listener only */
1511     {
1512         Mutex::Autolock lock(mCameraStatesLock);
1513         for (auto& i : mCameraStates) {
1514             // TODO: Update binder to use String16 for camera IDs and remove;
1515             int id = cameraIdToInt(i.first);
1516             if (id == -1) continue;
1517 
1518             listener->onStatusChanged(i.second->getStatus(), id);
1519         }
1520     }
1521 
1522     /* Immediately signal current torch status to this listener only */
1523     {
1524         Mutex::Autolock al(mTorchStatusMutex);
1525         for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
1526             String16 id = String16(mTorchStatusMap.keyAt(i).string());
1527             listener->onTorchStatusChanged(mTorchStatusMap.valueAt(i), id);
1528         }
1529     }
1530 
1531     return Status::ok();
1532 }
1533 
removeListener(const sp<ICameraServiceListener> & listener)1534 Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
1535     ATRACE_CALL();
1536 
1537     ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
1538 
1539     if (listener == 0) {
1540         ALOGE("%s: Listener must not be null", __FUNCTION__);
1541         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
1542     }
1543 
1544     Mutex::Autolock lock(mServiceLock);
1545 
1546     {
1547         Mutex::Autolock lock(mStatusListenerLock);
1548         for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
1549             if (IInterface::asBinder(*it) == IInterface::asBinder(listener)) {
1550                 mListenerList.erase(it);
1551                 return Status::ok();
1552             }
1553         }
1554     }
1555 
1556     ALOGW("%s: Tried to remove a listener %p which was not subscribed",
1557           __FUNCTION__, listener.get());
1558 
1559     return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
1560 }
1561 
getLegacyParameters(int cameraId,String16 * parameters)1562 Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
1563 
1564     ATRACE_CALL();
1565     ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1566 
1567     if (parameters == NULL) {
1568         ALOGE("%s: parameters must not be null", __FUNCTION__);
1569         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
1570     }
1571 
1572     Status ret = Status::ok();
1573 
1574     CameraParameters shimParams;
1575     if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
1576         // Error logged by caller
1577         return ret;
1578     }
1579 
1580     String8 shimParamsString8 = shimParams.flatten();
1581     String16 shimParamsString16 = String16(shimParamsString8);
1582 
1583     *parameters = shimParamsString16;
1584 
1585     return ret;
1586 }
1587 
supportsCameraApi(int cameraId,int apiVersion,bool * isSupported)1588 Status CameraService::supportsCameraApi(int cameraId, int apiVersion, bool *isSupported) {
1589     ATRACE_CALL();
1590 
1591     ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1592 
1593     switch (apiVersion) {
1594         case API_VERSION_1:
1595         case API_VERSION_2:
1596             break;
1597         default:
1598             String8 msg = String8::format("Unknown API version %d", apiVersion);
1599             ALOGE("%s: %s", __FUNCTION__, msg.string());
1600             return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
1601     }
1602 
1603     int facing = -1;
1604     int deviceVersion = getDeviceVersion(cameraId, &facing);
1605 
1606     switch(deviceVersion) {
1607         case CAMERA_DEVICE_API_VERSION_1_0:
1608         case CAMERA_DEVICE_API_VERSION_3_0:
1609         case CAMERA_DEVICE_API_VERSION_3_1:
1610             if (apiVersion == API_VERSION_2) {
1611                 ALOGV("%s: Camera id %d uses HAL version %d <3.2, doesn't support api2 without shim",
1612                         __FUNCTION__, cameraId, deviceVersion);
1613                 *isSupported = false;
1614             } else { // if (apiVersion == API_VERSION_1) {
1615                 ALOGV("%s: Camera id %d uses older HAL before 3.2, but api1 is always supported",
1616                         __FUNCTION__, cameraId);
1617                 *isSupported = true;
1618             }
1619             break;
1620         case CAMERA_DEVICE_API_VERSION_3_2:
1621         case CAMERA_DEVICE_API_VERSION_3_3:
1622         case CAMERA_DEVICE_API_VERSION_3_4:
1623             ALOGV("%s: Camera id %d uses HAL3.2 or newer, supports api1/api2 directly",
1624                     __FUNCTION__, cameraId);
1625             *isSupported = true;
1626             break;
1627         case -1: {
1628             String8 msg = String8::format("Unknown camera ID %d", cameraId);
1629             ALOGE("%s: %s", __FUNCTION__, msg.string());
1630             return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
1631         }
1632         default: {
1633             String8 msg = String8::format("Unknown device version %d for device %d",
1634                     deviceVersion, cameraId);
1635             ALOGE("%s: %s", __FUNCTION__, msg.string());
1636             return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
1637         }
1638     }
1639 
1640     return Status::ok();
1641 }
1642 
removeByClient(const BasicClient * client)1643 void CameraService::removeByClient(const BasicClient* client) {
1644     Mutex::Autolock lock(mServiceLock);
1645     for (auto& i : mActiveClientManager.getAll()) {
1646         auto clientSp = i->getValue();
1647         if (clientSp.get() == client) {
1648             mActiveClientManager.remove(i);
1649         }
1650     }
1651 }
1652 
evictClientIdByRemote(const wp<IBinder> & remote)1653 bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
1654     const int callingPid = getCallingPid();
1655     const int servicePid = getpid();
1656     bool ret = false;
1657     {
1658         // Acquire mServiceLock and prevent other clients from connecting
1659         std::unique_ptr<AutoConditionLock> lock =
1660                 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1661 
1662 
1663         std::vector<sp<BasicClient>> evicted;
1664         for (auto& i : mActiveClientManager.getAll()) {
1665             auto clientSp = i->getValue();
1666             if (clientSp.get() == nullptr) {
1667                 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1668                 mActiveClientManager.remove(i);
1669                 continue;
1670             }
1671             if (remote == clientSp->getRemote() && (callingPid == servicePid ||
1672                     callingPid == clientSp->getClientPid())) {
1673                 mActiveClientManager.remove(i);
1674                 evicted.push_back(clientSp);
1675 
1676                 // Notify the client of disconnection
1677                 clientSp->notifyError(
1678                         hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1679                         CaptureResultExtras());
1680             }
1681         }
1682 
1683         // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1684         // other clients from connecting in mServiceLockWrapper if held
1685         mServiceLock.unlock();
1686 
1687         // Do not clear caller identity, remote caller should be client proccess
1688 
1689         for (auto& i : evicted) {
1690             if (i.get() != nullptr) {
1691                 i->disconnect();
1692                 ret = true;
1693             }
1694         }
1695 
1696         // Reacquire mServiceLock
1697         mServiceLock.lock();
1698 
1699     } // lock is destroyed, allow further connect calls
1700 
1701     return ret;
1702 }
1703 
1704 
1705 /**
1706  * Check camera capabilities, such as support for basic color operation
1707  * Also check that the device HAL version is still in support
1708  */
checkCameraCapabilities(int id,camera_info info,int * latestStrangeCameraId)1709 int CameraService::checkCameraCapabilities(int id, camera_info info, int *latestStrangeCameraId) {
1710     // device_version undefined in CAMERA_MODULE_API_VERSION_1_0,
1711     // All CAMERA_MODULE_API_VERSION_1_0 devices are backward-compatible
1712     if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0) {
1713         // Verify the device version is in the supported range
1714         switch (info.device_version) {
1715             case CAMERA_DEVICE_API_VERSION_1_0:
1716             case CAMERA_DEVICE_API_VERSION_3_0:
1717             case CAMERA_DEVICE_API_VERSION_3_1:
1718             case CAMERA_DEVICE_API_VERSION_3_2:
1719             case CAMERA_DEVICE_API_VERSION_3_3:
1720             case CAMERA_DEVICE_API_VERSION_3_4:
1721                 // in support
1722                 break;
1723             case CAMERA_DEVICE_API_VERSION_2_0:
1724             case CAMERA_DEVICE_API_VERSION_2_1:
1725                 // no longer supported
1726             default:
1727                 ALOGE("%s: Device %d has HAL version %x, which is not supported",
1728                         __FUNCTION__, id, info.device_version);
1729                 String8 msg = String8::format(
1730                         "Unsupported device HAL version %x for device %d",
1731                         info.device_version, id);
1732                 logServiceError(msg.string(), NO_INIT);
1733                 return NO_INIT;
1734         }
1735     }
1736 
1737     // Assume all devices pre-v3.3 are backward-compatible
1738     bool isBackwardCompatible = true;
1739     if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0
1740             && info.device_version >= CAMERA_DEVICE_API_VERSION_3_3) {
1741         isBackwardCompatible = false;
1742         status_t res;
1743         camera_metadata_ro_entry_t caps;
1744         res = find_camera_metadata_ro_entry(
1745             info.static_camera_characteristics,
1746             ANDROID_REQUEST_AVAILABLE_CAPABILITIES,
1747             &caps);
1748         if (res != 0) {
1749             ALOGW("%s: Unable to find camera capabilities for camera device %d",
1750                     __FUNCTION__, id);
1751             caps.count = 0;
1752         }
1753         for (size_t i = 0; i < caps.count; i++) {
1754             if (caps.data.u8[i] ==
1755                     ANDROID_REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE) {
1756                 isBackwardCompatible = true;
1757                 break;
1758             }
1759         }
1760     }
1761 
1762     if (!isBackwardCompatible) {
1763         mNumberOfNormalCameras--;
1764         *latestStrangeCameraId = id;
1765     } else {
1766         if (id > *latestStrangeCameraId) {
1767             ALOGE("%s: Normal camera ID %d higher than strange camera ID %d. "
1768                     "This is not allowed due backward-compatibility requirements",
1769                     __FUNCTION__, id, *latestStrangeCameraId);
1770             logServiceError("Invalid order of camera devices", NO_INIT);
1771             mNumberOfCameras = 0;
1772             mNumberOfNormalCameras = 0;
1773             return NO_INIT;
1774         }
1775     }
1776     return OK;
1777 }
1778 
getCameraState(const String8 & cameraId) const1779 std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
1780         const String8& cameraId) const {
1781     std::shared_ptr<CameraState> state;
1782     {
1783         Mutex::Autolock lock(mCameraStatesLock);
1784         auto iter = mCameraStates.find(cameraId);
1785         if (iter != mCameraStates.end()) {
1786             state = iter->second;
1787         }
1788     }
1789     return state;
1790 }
1791 
removeClientLocked(const String8 & cameraId)1792 sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
1793     // Remove from active clients list
1794     auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
1795     if (clientDescriptorPtr == nullptr) {
1796         ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
1797                 cameraId.string());
1798         return sp<BasicClient>{nullptr};
1799     }
1800 
1801     return clientDescriptorPtr->getValue();
1802 }
1803 
doUserSwitch(const std::vector<int32_t> & newUserIds)1804 void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
1805     // Acquire mServiceLock and prevent other clients from connecting
1806     std::unique_ptr<AutoConditionLock> lock =
1807             AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1808 
1809     std::set<userid_t> newAllowedUsers;
1810     for (size_t i = 0; i < newUserIds.size(); i++) {
1811         if (newUserIds[i] < 0) {
1812             ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
1813                     __FUNCTION__, newUserIds[i]);
1814             return;
1815         }
1816         newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
1817     }
1818 
1819 
1820     if (newAllowedUsers == mAllowedUsers) {
1821         ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
1822         return;
1823     }
1824 
1825     logUserSwitch(mAllowedUsers, newAllowedUsers);
1826 
1827     mAllowedUsers = std::move(newAllowedUsers);
1828 
1829     // Current user has switched, evict all current clients.
1830     std::vector<sp<BasicClient>> evicted;
1831     for (auto& i : mActiveClientManager.getAll()) {
1832         auto clientSp = i->getValue();
1833 
1834         if (clientSp.get() == nullptr) {
1835             ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1836             continue;
1837         }
1838 
1839         // Don't evict clients that are still allowed.
1840         uid_t clientUid = clientSp->getClientUid();
1841         userid_t clientUserId = multiuser_get_user_id(clientUid);
1842         if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
1843             continue;
1844         }
1845 
1846         evicted.push_back(clientSp);
1847 
1848         String8 curTime = getFormattedCurrentTime();
1849 
1850         ALOGE("Evicting conflicting client for camera ID %s due to user change",
1851                 i->getKey().string());
1852 
1853         // Log the clients evicted
1854         logEvent(String8::format("EVICT device %s client held by package %s (PID %"
1855                 PRId32 ", priority %" PRId32 ")\n   - Evicted due to user switch.",
1856                 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1857                 i->getOwnerId(), i->getPriority()));
1858 
1859     }
1860 
1861     // Do not hold mServiceLock while disconnecting clients, but retain the condition
1862     // blocking other clients from connecting in mServiceLockWrapper if held.
1863     mServiceLock.unlock();
1864 
1865     // Clear caller identity temporarily so client disconnect PID checks work correctly
1866     int64_t token = IPCThreadState::self()->clearCallingIdentity();
1867 
1868     for (auto& i : evicted) {
1869         i->disconnect();
1870     }
1871 
1872     IPCThreadState::self()->restoreCallingIdentity(token);
1873 
1874     // Reacquire mServiceLock
1875     mServiceLock.lock();
1876 }
1877 
logEvent(const char * event)1878 void CameraService::logEvent(const char* event) {
1879     String8 curTime = getFormattedCurrentTime();
1880     Mutex::Autolock l(mLogLock);
1881     mEventLog.add(String8::format("%s : %s", curTime.string(), event));
1882 }
1883 
logDisconnected(const char * cameraId,int clientPid,const char * clientPackage)1884 void CameraService::logDisconnected(const char* cameraId, int clientPid,
1885         const char* clientPackage) {
1886     // Log the clients evicted
1887     logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
1888             clientPackage, clientPid));
1889 }
1890 
logConnected(const char * cameraId,int clientPid,const char * clientPackage)1891 void CameraService::logConnected(const char* cameraId, int clientPid,
1892         const char* clientPackage) {
1893     // Log the clients evicted
1894     logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
1895             clientPackage, clientPid));
1896 }
1897 
logRejected(const char * cameraId,int clientPid,const char * clientPackage,const char * reason)1898 void CameraService::logRejected(const char* cameraId, int clientPid,
1899         const char* clientPackage, const char* reason) {
1900     // Log the client rejected
1901     logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
1902             cameraId, clientPackage, clientPid, reason));
1903 }
1904 
logUserSwitch(const std::set<userid_t> & oldUserIds,const std::set<userid_t> & newUserIds)1905 void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
1906         const std::set<userid_t>& newUserIds) {
1907     String8 newUsers = toString(newUserIds);
1908     String8 oldUsers = toString(oldUserIds);
1909     // Log the new and old users
1910     logEvent(String8::format("USER_SWITCH previous allowed users: %s , current allowed users: %s",
1911             oldUsers.string(), newUsers.string()));
1912 }
1913 
logDeviceRemoved(const char * cameraId,const char * reason)1914 void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
1915     // Log the device removal
1916     logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
1917 }
1918 
logDeviceAdded(const char * cameraId,const char * reason)1919 void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
1920     // Log the device removal
1921     logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
1922 }
1923 
logClientDied(int clientPid,const char * reason)1924 void CameraService::logClientDied(int clientPid, const char* reason) {
1925     // Log the device removal
1926     logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
1927 }
1928 
logServiceError(const char * msg,int errorCode)1929 void CameraService::logServiceError(const char* msg, int errorCode) {
1930     String8 curTime = getFormattedCurrentTime();
1931     logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
1932 }
1933 
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)1934 status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
1935         uint32_t flags) {
1936 
1937     const int pid = getCallingPid();
1938     const int selfPid = getpid();
1939 
1940     // Permission checks
1941     switch (code) {
1942         case BnCameraService::NOTIFYSYSTEMEVENT: {
1943             if (pid != selfPid) {
1944                 // Ensure we're being called by system_server, or similar process with
1945                 // permissions to notify the camera service about system events
1946                 if (!checkCallingPermission(
1947                         String16("android.permission.CAMERA_SEND_SYSTEM_EVENTS"))) {
1948                     const int uid = getCallingUid();
1949                     ALOGE("Permission Denial: cannot send updates to camera service about system"
1950                             " events from pid=%d, uid=%d", pid, uid);
1951                     return PERMISSION_DENIED;
1952                 }
1953             }
1954             break;
1955         }
1956     }
1957 
1958     return BnCameraService::onTransact(code, data, reply, flags);
1959 }
1960 
1961 // We share the media players for shutter and recording sound for all clients.
1962 // A reference count is kept to determine when we will actually release the
1963 // media players.
1964 
newMediaPlayer(const char * file)1965 MediaPlayer* CameraService::newMediaPlayer(const char *file) {
1966     MediaPlayer* mp = new MediaPlayer();
1967     if (mp->setDataSource(NULL /* httpService */, file, NULL) == NO_ERROR) {
1968         mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
1969         mp->prepare();
1970     } else {
1971         ALOGE("Failed to load CameraService sounds: %s", file);
1972         return NULL;
1973     }
1974     return mp;
1975 }
1976 
loadSound()1977 void CameraService::loadSound() {
1978     ATRACE_CALL();
1979 
1980     Mutex::Autolock lock(mSoundLock);
1981     LOG1("CameraService::loadSound ref=%d", mSoundRef);
1982     if (mSoundRef++) return;
1983 
1984     mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
1985     mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
1986     mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
1987 }
1988 
releaseSound()1989 void CameraService::releaseSound() {
1990     Mutex::Autolock lock(mSoundLock);
1991     LOG1("CameraService::releaseSound ref=%d", mSoundRef);
1992     if (--mSoundRef) return;
1993 
1994     for (int i = 0; i < NUM_SOUNDS; i++) {
1995         if (mSoundPlayer[i] != 0) {
1996             mSoundPlayer[i]->disconnect();
1997             mSoundPlayer[i].clear();
1998         }
1999     }
2000 }
2001 
playSound(sound_kind kind)2002 void CameraService::playSound(sound_kind kind) {
2003     ATRACE_CALL();
2004 
2005     LOG1("playSound(%d)", kind);
2006     Mutex::Autolock lock(mSoundLock);
2007     sp<MediaPlayer> player = mSoundPlayer[kind];
2008     if (player != 0) {
2009         player->seekTo(0);
2010         player->start();
2011     }
2012 }
2013 
2014 // ----------------------------------------------------------------------------
2015 
Client(const sp<CameraService> & cameraService,const sp<ICameraClient> & cameraClient,const String16 & clientPackageName,int cameraId,int cameraFacing,int clientPid,uid_t clientUid,int servicePid)2016 CameraService::Client::Client(const sp<CameraService>& cameraService,
2017         const sp<ICameraClient>& cameraClient,
2018         const String16& clientPackageName,
2019         int cameraId, int cameraFacing,
2020         int clientPid, uid_t clientUid,
2021         int servicePid) :
2022         CameraService::BasicClient(cameraService,
2023                 IInterface::asBinder(cameraClient),
2024                 clientPackageName,
2025                 cameraId, cameraFacing,
2026                 clientPid, clientUid,
2027                 servicePid)
2028 {
2029     int callingPid = getCallingPid();
2030     LOG1("Client::Client E (pid %d, id %d)", callingPid, cameraId);
2031 
2032     mRemoteCallback = cameraClient;
2033 
2034     cameraService->loadSound();
2035 
2036     LOG1("Client::Client X (pid %d, id %d)", callingPid, cameraId);
2037 }
2038 
2039 // tear down the client
~Client()2040 CameraService::Client::~Client() {
2041     ALOGV("~Client");
2042     mDestructionStarted = true;
2043 
2044     mCameraService->releaseSound();
2045     // unconditionally disconnect. function is idempotent
2046     Client::disconnect();
2047 }
2048 
BasicClient(const sp<CameraService> & cameraService,const sp<IBinder> & remoteCallback,const String16 & clientPackageName,int cameraId,int cameraFacing,int clientPid,uid_t clientUid,int servicePid)2049 CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
2050         const sp<IBinder>& remoteCallback,
2051         const String16& clientPackageName,
2052         int cameraId, int cameraFacing,
2053         int clientPid, uid_t clientUid,
2054         int servicePid):
2055         mClientPackageName(clientPackageName), mDisconnected(false)
2056 {
2057     mCameraService = cameraService;
2058     mRemoteBinder = remoteCallback;
2059     mCameraId = cameraId;
2060     mCameraFacing = cameraFacing;
2061     mClientPid = clientPid;
2062     mClientUid = clientUid;
2063     mServicePid = servicePid;
2064     mOpsActive = false;
2065     mDestructionStarted = false;
2066 
2067     // In some cases the calling code has no access to the package it runs under.
2068     // For example, NDK camera API.
2069     // In this case we will get the packages for the calling UID and pick the first one
2070     // for attributing the app op. This will work correctly for runtime permissions
2071     // as for legacy apps we will toggle the app op for all packages in the UID.
2072     // The caveat is that the operation may be attributed to the wrong package and
2073     // stats based on app ops may be slightly off.
2074     if (mClientPackageName.size() <= 0) {
2075         sp<IServiceManager> sm = defaultServiceManager();
2076         sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2077         if (binder == 0) {
2078             ALOGE("Cannot get permission service");
2079             // Leave mClientPackageName unchanged (empty) and the further interaction
2080             // with camera will fail in BasicClient::startCameraOps
2081             return;
2082         }
2083 
2084         sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2085         Vector<String16> packages;
2086 
2087         permCtrl->getPackagesForUid(mClientUid, packages);
2088 
2089         if (packages.isEmpty()) {
2090             ALOGE("No packages for calling UID");
2091             // Leave mClientPackageName unchanged (empty) and the further interaction
2092             // with camera will fail in BasicClient::startCameraOps
2093             return;
2094         }
2095         mClientPackageName = packages[0];
2096     }
2097 }
2098 
~BasicClient()2099 CameraService::BasicClient::~BasicClient() {
2100     ALOGV("~BasicClient");
2101     mDestructionStarted = true;
2102 }
2103 
disconnect()2104 binder::Status CameraService::BasicClient::disconnect() {
2105     binder::Status res = Status::ok();
2106     if (mDisconnected) {
2107         return res;
2108     }
2109     mDisconnected = true;
2110 
2111     mCameraService->removeByClient(this);
2112     mCameraService->logDisconnected(String8::format("%d", mCameraId), mClientPid,
2113             String8(mClientPackageName));
2114 
2115     sp<IBinder> remote = getRemote();
2116     if (remote != nullptr) {
2117         remote->unlinkToDeath(mCameraService);
2118     }
2119 
2120     finishCameraOps();
2121     ALOGI("%s: Disconnected client for camera %d for PID %d", __FUNCTION__, mCameraId, mClientPid);
2122 
2123     // client shouldn't be able to call into us anymore
2124     mClientPid = 0;
2125 
2126     return res;
2127 }
2128 
dump(int,const Vector<String16> &)2129 status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2130     // No dumping of clients directly over Binder,
2131     // must go through CameraService::dump
2132     android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
2133             IPCThreadState::self()->getCallingUid(), NULL, 0);
2134     return OK;
2135 }
2136 
getPackageName() const2137 String16 CameraService::BasicClient::getPackageName() const {
2138     return mClientPackageName;
2139 }
2140 
2141 
getClientPid() const2142 int CameraService::BasicClient::getClientPid() const {
2143     return mClientPid;
2144 }
2145 
getClientUid() const2146 uid_t CameraService::BasicClient::getClientUid() const {
2147     return mClientUid;
2148 }
2149 
canCastToApiClient(apiLevel level) const2150 bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2151     // Defaults to API2.
2152     return level == API_2;
2153 }
2154 
startCameraOps()2155 status_t CameraService::BasicClient::startCameraOps() {
2156     ATRACE_CALL();
2157 
2158     int32_t res;
2159     // Notify app ops that the camera is not available
2160     mOpsCallback = new OpsCallback(this);
2161 
2162     {
2163         ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
2164               __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
2165     }
2166 
2167     mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA,
2168             mClientPackageName, mOpsCallback);
2169     res = mAppOpsManager.startOp(AppOpsManager::OP_CAMERA,
2170             mClientUid, mClientPackageName);
2171 
2172     if (res == AppOpsManager::MODE_ERRORED) {
2173         ALOGI("Camera %d: Access for \"%s\" has been revoked",
2174                 mCameraId, String8(mClientPackageName).string());
2175         return PERMISSION_DENIED;
2176     }
2177 
2178     if (res == AppOpsManager::MODE_IGNORED) {
2179         ALOGI("Camera %d: Access for \"%s\" has been restricted",
2180                 mCameraId, String8(mClientPackageName).string());
2181         // Return the same error as for device policy manager rejection
2182         return -EACCES;
2183     }
2184 
2185     mOpsActive = true;
2186 
2187     // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
2188     mCameraService->updateStatus(ICameraServiceListener::STATUS_NOT_AVAILABLE,
2189             String8::format("%d", mCameraId));
2190 
2191     // Transition device state to OPEN
2192     mCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
2193             String8::format("%d", mCameraId));
2194 
2195     return OK;
2196 }
2197 
finishCameraOps()2198 status_t CameraService::BasicClient::finishCameraOps() {
2199     ATRACE_CALL();
2200 
2201     // Check if startCameraOps succeeded, and if so, finish the camera op
2202     if (mOpsActive) {
2203         // Notify app ops that the camera is available again
2204         mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid,
2205                 mClientPackageName);
2206         mOpsActive = false;
2207 
2208         std::initializer_list<int32_t> rejected = {ICameraServiceListener::STATUS_NOT_PRESENT,
2209                 ICameraServiceListener::STATUS_ENUMERATING};
2210 
2211         // Transition to PRESENT if the camera is not in either of the rejected states
2212         mCameraService->updateStatus(ICameraServiceListener::STATUS_PRESENT,
2213                 String8::format("%d", mCameraId), rejected);
2214 
2215         // Transition device state to CLOSED
2216         mCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
2217                 String8::format("%d", mCameraId));
2218 
2219         // Notify flashlight that a camera device is closed.
2220         mCameraService->mFlashlight->deviceClosed(
2221                 String8::format("%d", mCameraId));
2222     }
2223     // Always stop watching, even if no camera op is active
2224     if (mOpsCallback != NULL) {
2225         mAppOpsManager.stopWatchingMode(mOpsCallback);
2226     }
2227     mOpsCallback.clear();
2228 
2229     return OK;
2230 }
2231 
opChanged(int32_t op,const String16 & packageName)2232 void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) {
2233     ATRACE_CALL();
2234 
2235     String8 name(packageName);
2236     String8 myName(mClientPackageName);
2237 
2238     if (op != AppOpsManager::OP_CAMERA) {
2239         ALOGW("Unexpected app ops notification received: %d", op);
2240         return;
2241     }
2242 
2243     int32_t res;
2244     res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA,
2245             mClientUid, mClientPackageName);
2246     ALOGV("checkOp returns: %d, %s ", res,
2247             res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
2248             res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
2249             res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
2250             "UNKNOWN");
2251 
2252     if (res != AppOpsManager::MODE_ALLOWED) {
2253         ALOGI("Camera %d: Access for \"%s\" revoked", mCameraId,
2254                 myName.string());
2255         // Reset the client PID to allow server-initiated disconnect,
2256         // and to prevent further calls by client.
2257         mClientPid = getCallingPid();
2258         CaptureResultExtras resultExtras; // a dummy result (invalid)
2259         notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_SERVICE, resultExtras);
2260         disconnect();
2261     }
2262 }
2263 
2264 // ----------------------------------------------------------------------------
2265 
2266 // Provide client strong pointer for callbacks.
getClientFromCookie(void * user)2267 sp<CameraService::Client> CameraService::Client::getClientFromCookie(void* user) {
2268     String8 cameraId = String8::format("%d", (int)(intptr_t) user);
2269     auto clientDescriptor = gCameraService->mActiveClientManager.get(cameraId);
2270     if (clientDescriptor != nullptr) {
2271         return sp<Client>{
2272                 static_cast<Client*>(clientDescriptor->getValue().get())};
2273     }
2274     return sp<Client>{nullptr};
2275 }
2276 
notifyError(int32_t errorCode,const CaptureResultExtras & resultExtras)2277 void CameraService::Client::notifyError(int32_t errorCode,
2278         const CaptureResultExtras& resultExtras) {
2279     (void) errorCode;
2280     (void) resultExtras;
2281     if (mRemoteCallback != NULL) {
2282         mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
2283     } else {
2284         ALOGE("mRemoteCallback is NULL!!");
2285     }
2286 }
2287 
2288 // NOTE: function is idempotent
disconnect()2289 binder::Status CameraService::Client::disconnect() {
2290     ALOGV("Client::disconnect");
2291     return BasicClient::disconnect();
2292 }
2293 
canCastToApiClient(apiLevel level) const2294 bool CameraService::Client::canCastToApiClient(apiLevel level) const {
2295     return level == API_1;
2296 }
2297 
OpsCallback(wp<BasicClient> client)2298 CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
2299         mClient(client) {
2300 }
2301 
opChanged(int32_t op,const String16 & packageName)2302 void CameraService::Client::OpsCallback::opChanged(int32_t op,
2303         const String16& packageName) {
2304     sp<BasicClient> client = mClient.promote();
2305     if (client != NULL) {
2306         client->opChanged(op, packageName);
2307     }
2308 }
2309 
2310 // ----------------------------------------------------------------------------
2311 //                  CameraState
2312 // ----------------------------------------------------------------------------
2313 
CameraState(const String8 & id,int cost,const std::set<String8> & conflicting)2314 CameraService::CameraState::CameraState(const String8& id, int cost,
2315         const std::set<String8>& conflicting) : mId(id),
2316         mStatus(ICameraServiceListener::STATUS_PRESENT), mCost(cost), mConflicting(conflicting) {}
2317 
~CameraState()2318 CameraService::CameraState::~CameraState() {}
2319 
getStatus() const2320 int32_t CameraService::CameraState::getStatus() const {
2321     Mutex::Autolock lock(mStatusLock);
2322     return mStatus;
2323 }
2324 
getShimParams() const2325 CameraParameters CameraService::CameraState::getShimParams() const {
2326     return mShimParams;
2327 }
2328 
setShimParams(const CameraParameters & params)2329 void CameraService::CameraState::setShimParams(const CameraParameters& params) {
2330     mShimParams = params;
2331 }
2332 
getCost() const2333 int CameraService::CameraState::getCost() const {
2334     return mCost;
2335 }
2336 
getConflicting() const2337 std::set<String8> CameraService::CameraState::getConflicting() const {
2338     return mConflicting;
2339 }
2340 
getId() const2341 String8 CameraService::CameraState::getId() const {
2342     return mId;
2343 }
2344 
2345 // ----------------------------------------------------------------------------
2346 //                  ClientEventListener
2347 // ----------------------------------------------------------------------------
2348 
onClientAdded(const resource_policy::ClientDescriptor<String8,sp<CameraService::BasicClient>> & descriptor)2349 void CameraService::ClientEventListener::onClientAdded(
2350         const resource_policy::ClientDescriptor<String8,
2351         sp<CameraService::BasicClient>>& descriptor) {
2352     auto basicClient = descriptor.getValue();
2353     if (basicClient.get() != nullptr) {
2354         BatteryNotifier& notifier(BatteryNotifier::getInstance());
2355         notifier.noteStartCamera(descriptor.getKey(),
2356                 static_cast<int>(basicClient->getClientUid()));
2357     }
2358 }
2359 
onClientRemoved(const resource_policy::ClientDescriptor<String8,sp<CameraService::BasicClient>> & descriptor)2360 void CameraService::ClientEventListener::onClientRemoved(
2361         const resource_policy::ClientDescriptor<String8,
2362         sp<CameraService::BasicClient>>& descriptor) {
2363     auto basicClient = descriptor.getValue();
2364     if (basicClient.get() != nullptr) {
2365         BatteryNotifier& notifier(BatteryNotifier::getInstance());
2366         notifier.noteStopCamera(descriptor.getKey(),
2367                 static_cast<int>(basicClient->getClientUid()));
2368     }
2369 }
2370 
2371 
2372 // ----------------------------------------------------------------------------
2373 //                  CameraClientManager
2374 // ----------------------------------------------------------------------------
2375 
CameraClientManager()2376 CameraService::CameraClientManager::CameraClientManager() {
2377     setListener(std::make_shared<ClientEventListener>());
2378 }
2379 
~CameraClientManager()2380 CameraService::CameraClientManager::~CameraClientManager() {}
2381 
getCameraClient(const String8 & id) const2382 sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
2383         const String8& id) const {
2384     auto descriptor = get(id);
2385     if (descriptor == nullptr) {
2386         return sp<BasicClient>{nullptr};
2387     }
2388     return descriptor->getValue();
2389 }
2390 
toString() const2391 String8 CameraService::CameraClientManager::toString() const {
2392     auto all = getAll();
2393     String8 ret("[");
2394     bool hasAny = false;
2395     for (auto& i : all) {
2396         hasAny = true;
2397         String8 key = i->getKey();
2398         int32_t cost = i->getCost();
2399         int32_t pid = i->getOwnerId();
2400         int32_t priority = i->getPriority();
2401         auto conflicting = i->getConflicting();
2402         auto clientSp = i->getValue();
2403         String8 packageName;
2404         userid_t clientUserId = 0;
2405         if (clientSp.get() != nullptr) {
2406             packageName = String8{clientSp->getPackageName()};
2407             uid_t clientUid = clientSp->getClientUid();
2408             clientUserId = multiuser_get_user_id(clientUid);
2409         }
2410         ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Priority: %"
2411                 PRId32 ", ", key.string(), cost, pid, priority);
2412 
2413         if (clientSp.get() != nullptr) {
2414             ret.appendFormat("User Id: %d, ", clientUserId);
2415         }
2416         if (packageName.size() != 0) {
2417             ret.appendFormat("Client Package Name: %s", packageName.string());
2418         }
2419 
2420         ret.append(", Conflicting Client Devices: {");
2421         for (auto& j : conflicting) {
2422             ret.appendFormat("%s, ", j.string());
2423         }
2424         ret.append("})");
2425     }
2426     if (hasAny) ret.append("\n");
2427     ret.append("]\n");
2428     return ret;
2429 }
2430 
makeClientDescriptor(const String8 & key,const sp<BasicClient> & value,int32_t cost,const std::set<String8> & conflictingKeys,int32_t priority,int32_t ownerId)2431 CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2432         const String8& key, const sp<BasicClient>& value, int32_t cost,
2433         const std::set<String8>& conflictingKeys, int32_t priority, int32_t ownerId) {
2434 
2435     return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
2436             key, value, cost, conflictingKeys, priority, ownerId);
2437 }
2438 
makeClientDescriptor(const sp<BasicClient> & value,const CameraService::DescriptorPtr & partial)2439 CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2440         const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
2441     return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
2442             partial->getConflicting(), partial->getPriority(), partial->getOwnerId());
2443 }
2444 
2445 // ----------------------------------------------------------------------------
2446 
2447 static const int kDumpLockRetries = 50;
2448 static const int kDumpLockSleep = 60000;
2449 
tryLock(Mutex & mutex)2450 static bool tryLock(Mutex& mutex)
2451 {
2452     bool locked = false;
2453     for (int i = 0; i < kDumpLockRetries; ++i) {
2454         if (mutex.tryLock() == NO_ERROR) {
2455             locked = true;
2456             break;
2457         }
2458         usleep(kDumpLockSleep);
2459     }
2460     return locked;
2461 }
2462 
dump(int fd,const Vector<String16> & args)2463 status_t CameraService::dump(int fd, const Vector<String16>& args) {
2464     ATRACE_CALL();
2465 
2466     String8 result("Dump of the Camera Service:\n");
2467     if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
2468         result = result.format("Permission Denial: "
2469                 "can't dump CameraService from pid=%d, uid=%d\n",
2470                 getCallingPid(),
2471                 getCallingUid());
2472         write(fd, result.string(), result.size());
2473     } else {
2474         bool locked = tryLock(mServiceLock);
2475         // failed to lock - CameraService is probably deadlocked
2476         if (!locked) {
2477             result.append("CameraService may be deadlocked\n");
2478             write(fd, result.string(), result.size());
2479         }
2480 
2481         bool hasClient = false;
2482         if (!mModule) {
2483             result = String8::format("No camera module available!\n");
2484             write(fd, result.string(), result.size());
2485 
2486             // Dump event log for error information
2487             dumpEventLog(fd);
2488 
2489             if (locked) mServiceLock.unlock();
2490             return NO_ERROR;
2491         }
2492 
2493         result = String8::format("Camera module HAL API version: 0x%x\n", mModule->getHalApiVersion());
2494         result.appendFormat("Camera module API version: 0x%x\n", mModule->getModuleApiVersion());
2495         result.appendFormat("Camera module name: %s\n", mModule->getModuleName());
2496         result.appendFormat("Camera module author: %s\n", mModule->getModuleAuthor());
2497         result.appendFormat("Number of camera devices: %d\n", mNumberOfCameras);
2498         result.appendFormat("Number of normal camera devices: %d\n", mNumberOfNormalCameras);
2499         String8 activeClientString = mActiveClientManager.toString();
2500         result.appendFormat("Active Camera Clients:\n%s", activeClientString.string());
2501         result.appendFormat("Allowed users:\n%s\n", toString(mAllowedUsers).string());
2502 
2503         sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
2504         if (desc == NULL) {
2505             result.appendFormat("Vendor tags left unimplemented.\n");
2506         } else {
2507             result.appendFormat("Vendor tag definitions:\n");
2508         }
2509 
2510         write(fd, result.string(), result.size());
2511 
2512         if (desc != NULL) {
2513             desc->dump(fd, /*verbosity*/2, /*indentation*/4);
2514         }
2515 
2516         dumpEventLog(fd);
2517 
2518         bool stateLocked = tryLock(mCameraStatesLock);
2519         if (!stateLocked) {
2520             result = String8::format("CameraStates in use, may be deadlocked\n");
2521             write(fd, result.string(), result.size());
2522         }
2523 
2524         for (auto& state : mCameraStates) {
2525             String8 cameraId = state.first;
2526             result = String8::format("Camera %s information:\n", cameraId.string());
2527             camera_info info;
2528 
2529             // TODO: Change getCameraInfo + HAL to use String cameraIds
2530             status_t rc = mModule->getCameraInfo(cameraIdToInt(cameraId), &info);
2531             if (rc != OK) {
2532                 result.appendFormat("  Error reading static information!\n");
2533                 write(fd, result.string(), result.size());
2534             } else {
2535                 result.appendFormat("  Facing: %s\n",
2536                         info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT");
2537                 result.appendFormat("  Orientation: %d\n", info.orientation);
2538                 int deviceVersion;
2539                 if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0) {
2540                     deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
2541                 } else {
2542                     deviceVersion = info.device_version;
2543                 }
2544 
2545                 auto conflicting = state.second->getConflicting();
2546                 result.appendFormat("  Resource Cost: %d\n", state.second->getCost());
2547                 result.appendFormat("  Conflicting Devices:");
2548                 for (auto& id : conflicting) {
2549                     result.appendFormat(" %s", id.string());
2550                 }
2551                 if (conflicting.size() == 0) {
2552                     result.appendFormat(" NONE");
2553                 }
2554                 result.appendFormat("\n");
2555 
2556                 result.appendFormat("  Device version: %#x\n", deviceVersion);
2557                 if (deviceVersion >= CAMERA_DEVICE_API_VERSION_3_0) {
2558                     result.appendFormat("  Device static metadata:\n");
2559                     write(fd, result.string(), result.size());
2560                     dump_indented_camera_metadata(info.static_camera_characteristics,
2561                             fd, /*verbosity*/2, /*indentation*/4);
2562                 } else {
2563                     write(fd, result.string(), result.size());
2564                 }
2565 
2566                 CameraParameters p = state.second->getShimParams();
2567                 if (!p.isEmpty()) {
2568                     result = String8::format("  Camera1 API shim is using parameters:\n        ");
2569                     write(fd, result.string(), result.size());
2570                     p.dump(fd, args);
2571                 }
2572             }
2573 
2574             auto clientDescriptor = mActiveClientManager.get(cameraId);
2575             if (clientDescriptor == nullptr) {
2576                 result = String8::format("  Device %s is closed, no client instance\n",
2577                         cameraId.string());
2578                 write(fd, result.string(), result.size());
2579                 continue;
2580             }
2581             hasClient = true;
2582             result = String8::format("  Device %s is open. Client instance dump:\n\n",
2583                     cameraId.string());
2584             result.appendFormat("Client priority level: %d\n", clientDescriptor->getPriority());
2585             result.appendFormat("Client PID: %d\n", clientDescriptor->getOwnerId());
2586 
2587             auto client = clientDescriptor->getValue();
2588             result.appendFormat("Client package: %s\n",
2589                     String8(client->getPackageName()).string());
2590             write(fd, result.string(), result.size());
2591 
2592             client->dumpClient(fd, args);
2593         }
2594 
2595         if (stateLocked) mCameraStatesLock.unlock();
2596 
2597         if (!hasClient) {
2598             result = String8::format("\nNo active camera clients yet.\n");
2599             write(fd, result.string(), result.size());
2600         }
2601 
2602         if (locked) mServiceLock.unlock();
2603 
2604         // Dump camera traces if there were any
2605         write(fd, "\n", 1);
2606         camera3::CameraTraces::dump(fd, args);
2607 
2608         // Process dump arguments, if any
2609         int n = args.size();
2610         String16 verboseOption("-v");
2611         String16 unreachableOption("--unreachable");
2612         for (int i = 0; i < n; i++) {
2613             if (args[i] == verboseOption) {
2614                 // change logging level
2615                 if (i + 1 >= n) continue;
2616                 String8 levelStr(args[i+1]);
2617                 int level = atoi(levelStr.string());
2618                 result = String8::format("\nSetting log level to %d.\n", level);
2619                 setLogLevel(level);
2620                 write(fd, result.string(), result.size());
2621             } else if (args[i] == unreachableOption) {
2622                 // Dump memory analysis
2623                 // TODO - should limit be an argument parameter?
2624                 UnreachableMemoryInfo info;
2625                 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
2626                 if (!success) {
2627                     dprintf(fd, "\nUnable to dump unreachable memory. "
2628                             "Try disabling SELinux enforcement.\n");
2629                 } else {
2630                     dprintf(fd, "\nDumping unreachable memory:\n");
2631                     std::string s = info.ToString(/*log_contents*/ true);
2632                     write(fd, s.c_str(), s.size());
2633                 }
2634             }
2635         }
2636     }
2637     return NO_ERROR;
2638 }
2639 
dumpEventLog(int fd)2640 void CameraService::dumpEventLog(int fd) {
2641     String8 result = String8("\nPrior client events (most recent at top):\n");
2642 
2643     Mutex::Autolock l(mLogLock);
2644     for (const auto& msg : mEventLog) {
2645         result.appendFormat("  %s\n", msg.string());
2646     }
2647 
2648     if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
2649         result.append("  ...\n");
2650     } else if (mEventLog.size() == 0) {
2651         result.append("  [no events yet]\n");
2652     }
2653     result.append("\n");
2654 
2655     write(fd, result.string(), result.size());
2656 }
2657 
handleTorchClientBinderDied(const wp<IBinder> & who)2658 void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
2659     Mutex::Autolock al(mTorchClientMapMutex);
2660     for (size_t i = 0; i < mTorchClientMap.size(); i++) {
2661         if (mTorchClientMap[i] == who) {
2662             // turn off the torch mode that was turned on by dead client
2663             String8 cameraId = mTorchClientMap.keyAt(i);
2664             status_t res = mFlashlight->setTorchMode(cameraId, false);
2665             if (res) {
2666                 ALOGE("%s: torch client died but couldn't turn off torch: "
2667                     "%s (%d)", __FUNCTION__, strerror(-res), res);
2668                 return;
2669             }
2670             mTorchClientMap.removeItemsAt(i);
2671             break;
2672         }
2673     }
2674 }
2675 
binderDied(const wp<IBinder> & who)2676 /*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
2677 
2678     /**
2679       * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
2680       * binder driver
2681       */
2682 
2683     logClientDied(getCallingPid(), String8("Binder died unexpectedly"));
2684 
2685     // check torch client
2686     handleTorchClientBinderDied(who);
2687 
2688     // check camera device client
2689     if(!evictClientIdByRemote(who)) {
2690         ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
2691         return;
2692     }
2693 
2694     ALOGE("%s: Java client's binder died, removing it from the list of active clients",
2695             __FUNCTION__);
2696 }
2697 
updateStatus(int32_t status,const String8 & cameraId)2698 void CameraService::updateStatus(int32_t status, const String8& cameraId) {
2699     updateStatus(status, cameraId, {});
2700 }
2701 
updateStatus(int32_t status,const String8 & cameraId,std::initializer_list<int32_t> rejectSourceStates)2702 void CameraService::updateStatus(int32_t status, const String8& cameraId,
2703         std::initializer_list<int32_t> rejectSourceStates) {
2704     // Do not lock mServiceLock here or can get into a deadlock from
2705     // connect() -> disconnect -> updateStatus
2706 
2707     auto state = getCameraState(cameraId);
2708 
2709     if (state == nullptr) {
2710         ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
2711                 cameraId.string());
2712         return;
2713     }
2714 
2715     // Update the status for this camera state, then send the onStatusChangedCallbacks to each
2716     // of the listeners with both the mStatusStatus and mStatusListenerLock held
2717     state->updateStatus(status, cameraId, rejectSourceStates, [this]
2718             (const String8& cameraId, int32_t status) {
2719 
2720             if (status != ICameraServiceListener::STATUS_ENUMERATING) {
2721                 // Update torch status if it has a flash unit.
2722                 Mutex::Autolock al(mTorchStatusMutex);
2723                 int32_t torchStatus;
2724                 if (getTorchStatusLocked(cameraId, &torchStatus) !=
2725                         NAME_NOT_FOUND) {
2726                     int32_t newTorchStatus =
2727                             status == ICameraServiceListener::STATUS_PRESENT ?
2728                             ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF :
2729                             ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
2730                     if (torchStatus != newTorchStatus) {
2731                         onTorchStatusChangedLocked(cameraId, newTorchStatus);
2732                     }
2733                 }
2734             }
2735 
2736             Mutex::Autolock lock(mStatusListenerLock);
2737 
2738             for (auto& listener : mListenerList) {
2739                 // TODO: Refactor status listeners to use strings for Camera IDs and remove this.
2740                 int id = cameraIdToInt(cameraId);
2741                 if (id != -1) listener->onStatusChanged(status, id);
2742             }
2743         });
2744 }
2745 
updateProxyDeviceState(ICameraServiceProxy::CameraState newState,const String8 & cameraId)2746 void CameraService::updateProxyDeviceState(ICameraServiceProxy::CameraState newState,
2747         const String8& cameraId) {
2748     sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
2749     if (proxyBinder == nullptr) return;
2750     String16 id(cameraId);
2751     proxyBinder->notifyCameraState(id, newState);
2752 }
2753 
getTorchStatusLocked(const String8 & cameraId,int32_t * status) const2754 status_t CameraService::getTorchStatusLocked(
2755         const String8& cameraId,
2756         int32_t *status) const {
2757     if (!status) {
2758         return BAD_VALUE;
2759     }
2760     ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2761     if (index == NAME_NOT_FOUND) {
2762         // invalid camera ID or the camera doesn't have a flash unit
2763         return NAME_NOT_FOUND;
2764     }
2765 
2766     *status = mTorchStatusMap.valueAt(index);
2767     return OK;
2768 }
2769 
setTorchStatusLocked(const String8 & cameraId,int32_t status)2770 status_t CameraService::setTorchStatusLocked(const String8& cameraId,
2771         int32_t status) {
2772     ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2773     if (index == NAME_NOT_FOUND) {
2774         return BAD_VALUE;
2775     }
2776     int32_t& item =
2777             mTorchStatusMap.editValueAt(index);
2778     item = status;
2779 
2780     return OK;
2781 }
2782 
2783 }; // namespace android
2784