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