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