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 #ifndef ANDROID_SERVERS_CAMERA_CAMERASERVICE_H
18 #define ANDROID_SERVERS_CAMERA_CAMERASERVICE_H
19 
20 #include <android/hardware/BnCameraService.h>
21 #include <android/hardware/BnSensorPrivacyListener.h>
22 #include <android/hardware/ICameraServiceListener.h>
23 #include <android/hardware/ICameraServiceProxy.h>
24 
25 #include <cutils/multiuser.h>
26 #include <utils/Vector.h>
27 #include <utils/KeyedVector.h>
28 #include <binder/ActivityManager.h>
29 #include <binder/AppOpsManager.h>
30 #include <binder/BinderService.h>
31 #include <binder/IAppOpsCallback.h>
32 #include <binder/IUidObserver.h>
33 #include <hardware/camera.h>
34 #include <sensorprivacy/SensorPrivacyManager.h>
35 
36 #include <android/hardware/camera/common/1.0/types.h>
37 
38 #include <camera/VendorTagDescriptor.h>
39 #include <camera/CaptureResult.h>
40 #include <camera/CameraParameters.h>
41 
42 #include "CameraFlashlight.h"
43 
44 #include "common/CameraProviderManager.h"
45 #include "media/RingBuffer.h"
46 #include "utils/AutoConditionLock.h"
47 #include "utils/ClientManager.h"
48 
49 #include <set>
50 #include <string>
51 #include <map>
52 #include <memory>
53 #include <optional>
54 #include <utility>
55 #include <unordered_map>
56 #include <unordered_set>
57 
58 namespace android {
59 
60 extern volatile int32_t gLogLevel;
61 
62 class MemoryHeapBase;
63 class MediaPlayer;
64 
65 class CameraService :
66     public BinderService<CameraService>,
67     public virtual ::android::hardware::BnCameraService,
68     public virtual IBinder::DeathRecipient,
69     public virtual CameraProviderManager::StatusListener
70 {
71     friend class BinderService<CameraService>;
72     friend class CameraClient;
73 public:
74     class Client;
75     class BasicClient;
76 
77     // The effective API level.  The Camera2 API running in LEGACY mode counts as API_1.
78     enum apiLevel {
79         API_1 = 1,
80         API_2 = 2
81     };
82 
83     // 3 second busy timeout when other clients are connecting
84     static const nsecs_t DEFAULT_CONNECT_TIMEOUT_NS = 3000000000;
85 
86     // 1 second busy timeout when other clients are disconnecting
87     static const nsecs_t DEFAULT_DISCONNECT_TIMEOUT_NS = 1000000000;
88 
89     // Default number of messages to store in eviction log
90     static const size_t DEFAULT_EVENT_LOG_LENGTH = 100;
91 
92     // Event log ID
93     static const int SN_EVENT_LOG_ID = 0x534e4554;
94 
95     // Implementation of BinderService<T>
getServiceName()96     static char const* getServiceName() { return "media.camera"; }
97 
98                         CameraService();
99     virtual             ~CameraService();
100 
101     /////////////////////////////////////////////////////////////////////
102     // HAL Callbacks - implements CameraProviderManager::StatusListener
103 
104     virtual void        onDeviceStatusChanged(const String8 &cameraId,
105             hardware::camera::common::V1_0::CameraDeviceStatus newHalStatus) override;
106     virtual void        onTorchStatusChanged(const String8& cameraId,
107             hardware::camera::common::V1_0::TorchModeStatus newStatus) override;
108     virtual void        onNewProviderRegistered() override;
109 
110     /////////////////////////////////////////////////////////////////////
111     // ICameraService
112     virtual binder::Status     getNumberOfCameras(int32_t type, int32_t* numCameras);
113 
114     virtual binder::Status     getCameraInfo(int cameraId,
115             hardware::CameraInfo* cameraInfo);
116     virtual binder::Status     getCameraCharacteristics(const String16& cameraId,
117             CameraMetadata* cameraInfo);
118     virtual binder::Status     getCameraVendorTagDescriptor(
119             /*out*/
120             hardware::camera2::params::VendorTagDescriptor* desc);
121     virtual binder::Status     getCameraVendorTagCache(
122             /*out*/
123             hardware::camera2::params::VendorTagDescriptorCache* cache);
124 
125     virtual binder::Status     connect(const sp<hardware::ICameraClient>& cameraClient,
126             int32_t cameraId, const String16& clientPackageName,
127             int32_t clientUid, int clientPid,
128             /*out*/
129             sp<hardware::ICamera>* device);
130 
131     virtual binder::Status     connectLegacy(const sp<hardware::ICameraClient>& cameraClient,
132             int32_t cameraId, int32_t halVersion,
133             const String16& clientPackageName, int32_t clientUid,
134             /*out*/
135             sp<hardware::ICamera>* device);
136 
137     virtual binder::Status     connectDevice(
138             const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb, const String16& cameraId,
139             const String16& clientPackageName, int32_t clientUid,
140             /*out*/
141             sp<hardware::camera2::ICameraDeviceUser>* device);
142 
143     virtual binder::Status    addListener(const sp<hardware::ICameraServiceListener>& listener,
144             /*out*/
145             std::vector<hardware::CameraStatus>* cameraStatuses);
146     virtual binder::Status    removeListener(
147             const sp<hardware::ICameraServiceListener>& listener);
148 
149     virtual binder::Status    getLegacyParameters(
150             int32_t cameraId,
151             /*out*/
152             String16* parameters);
153 
154     virtual binder::Status    setTorchMode(const String16& cameraId, bool enabled,
155             const sp<IBinder>& clientBinder);
156 
157     virtual binder::Status    notifySystemEvent(int32_t eventId,
158             const std::vector<int32_t>& args);
159 
160     virtual binder::Status    notifyDeviceStateChange(int64_t newState);
161 
162     // OK = supports api of that version, -EOPNOTSUPP = does not support
163     virtual binder::Status    supportsCameraApi(
164             const String16& cameraId, int32_t apiVersion,
165             /*out*/
166             bool *isSupported);
167 
168     virtual binder::Status    isHiddenPhysicalCamera(
169             const String16& cameraId,
170             /*out*/
171             bool *isSupported);
172 
173     // Extra permissions checks
174     virtual status_t    onTransact(uint32_t code, const Parcel& data,
175                                    Parcel* reply, uint32_t flags);
176 
177     virtual status_t    dump(int fd, const Vector<String16>& args);
178 
179     virtual status_t    shellCommand(int in, int out, int err, const Vector<String16>& args);
180 
181     binder::Status      addListenerHelper(const sp<hardware::ICameraServiceListener>& listener,
182             /*out*/
183             std::vector<hardware::CameraStatus>* cameraStatuses, bool isVendor = false);
184 
185     // Monitored UIDs availability notification
186     void                notifyMonitoredUids();
187 
188     /////////////////////////////////////////////////////////////////////
189     // Client functionality
190 
191     enum sound_kind {
192         SOUND_SHUTTER = 0,
193         SOUND_RECORDING_START = 1,
194         SOUND_RECORDING_STOP = 2,
195         NUM_SOUNDS
196     };
197 
198     void                playSound(sound_kind kind);
199     void                loadSoundLocked(sound_kind kind);
200     void                decreaseSoundRef();
201     void                increaseSoundRef();
202     /**
203      * Update the state of a given camera device (open/close/active/idle) with
204      * the camera proxy service in the system service
205      */
206     static void         updateProxyDeviceState(
207             int newState,
208             const String8& cameraId,
209             int facing,
210             const String16& clientName,
211             int apiLevel);
212 
213     /////////////////////////////////////////////////////////////////////
214     // CameraDeviceFactory functionality
215     int                 getDeviceVersion(const String8& cameraId, int* facing = NULL);
216 
217     /////////////////////////////////////////////////////////////////////
218     // Shared utilities
219     static binder::Status filterGetInfoErrorCode(status_t err);
220 
221     /////////////////////////////////////////////////////////////////////
222     // CameraClient functionality
223 
224     class BasicClient : public virtual RefBase {
225     public:
226         virtual status_t       initialize(sp<CameraProviderManager> manager,
227                 const String8& monitorTags) = 0;
228         virtual binder::Status disconnect();
229 
230         // because we can't virtually inherit IInterface, which breaks
231         // virtual inheritance
232         virtual sp<IBinder>    asBinderWrapper() = 0;
233 
234         // Return the remote callback binder object (e.g. ICameraDeviceCallbacks)
getRemote()235         sp<IBinder>            getRemote() {
236             return mRemoteBinder;
237         }
238 
239         // Disallows dumping over binder interface
240         virtual status_t dump(int fd, const Vector<String16>& args);
241         // Internal dump method to be called by CameraService
242         virtual status_t dumpClient(int fd, const Vector<String16>& args) = 0;
243 
244         // Return the package name for this client
245         virtual String16 getPackageName() const;
246 
247         // Notify client about a fatal error
248         virtual void notifyError(int32_t errorCode,
249                 const CaptureResultExtras& resultExtras) = 0;
250 
251         // Get the UID of the application client using this
252         virtual uid_t getClientUid() const;
253 
254         // Get the PID of the application client using this
255         virtual int getClientPid() const;
256 
257         // Check what API level is used for this client. This is used to determine which
258         // superclass this can be cast to.
259         virtual bool canCastToApiClient(apiLevel level) const;
260 
261         // Block the client form using the camera
262         virtual void block();
263     protected:
264         BasicClient(const sp<CameraService>& cameraService,
265                 const sp<IBinder>& remoteCallback,
266                 const String16& clientPackageName,
267                 const String8& cameraIdStr,
268                 int cameraFacing,
269                 int clientPid,
270                 uid_t clientUid,
271                 int servicePid);
272 
273         virtual ~BasicClient();
274 
275         // the instance is in the middle of destruction. When this is set,
276         // the instance should not be accessed from callback.
277         // CameraService's mClientLock should be acquired to access this.
278         // - subclasses should set this to true in their destructors.
279         bool                            mDestructionStarted;
280 
281         // these are initialized in the constructor.
282         static sp<CameraService>        sCameraService;
283         const String8                   mCameraIdStr;
284         const int                       mCameraFacing;
285         String16                        mClientPackageName;
286         pid_t                           mClientPid;
287         const uid_t                     mClientUid;
288         const pid_t                     mServicePid;
289         bool                            mDisconnected;
290 
291         // - The app-side Binder interface to receive callbacks from us
292         sp<IBinder>                     mRemoteBinder;   // immutable after constructor
293 
294         // permissions management
295         status_t                        startCameraOps();
296         status_t                        finishCameraOps();
297 
298     private:
299         std::unique_ptr<AppOpsManager>  mAppOpsManager = nullptr;
300 
301         class OpsCallback : public BnAppOpsCallback {
302         public:
303             explicit OpsCallback(wp<BasicClient> client);
304             virtual void opChanged(int32_t op, const String16& packageName);
305 
306         private:
307             wp<BasicClient> mClient;
308 
309         }; // class OpsCallback
310 
311         sp<OpsCallback> mOpsCallback;
312         // Track whether startCameraOps was called successfully, to avoid
313         // finishing what we didn't start.
314         bool            mOpsActive;
315 
316         // IAppOpsCallback interface, indirected through opListener
317         virtual void opChanged(int32_t op, const String16& packageName);
318     }; // class BasicClient
319 
320     class Client : public hardware::BnCamera, public BasicClient
321     {
322     public:
323         typedef hardware::ICameraClient TCamCallbacks;
324 
325         // ICamera interface (see ICamera for details)
326         virtual binder::Status disconnect();
327         virtual status_t      connect(const sp<hardware::ICameraClient>& client) = 0;
328         virtual status_t      lock() = 0;
329         virtual status_t      unlock() = 0;
330         virtual status_t      setPreviewTarget(const sp<IGraphicBufferProducer>& bufferProducer)=0;
331         virtual void          setPreviewCallbackFlag(int flag) = 0;
332         virtual status_t      setPreviewCallbackTarget(
333                 const sp<IGraphicBufferProducer>& callbackProducer) = 0;
334         virtual status_t      startPreview() = 0;
335         virtual void          stopPreview() = 0;
336         virtual bool          previewEnabled() = 0;
337         virtual status_t      setVideoBufferMode(int32_t videoBufferMode) = 0;
338         virtual status_t      startRecording() = 0;
339         virtual void          stopRecording() = 0;
340         virtual bool          recordingEnabled() = 0;
341         virtual void          releaseRecordingFrame(const sp<IMemory>& mem) = 0;
342         virtual status_t      autoFocus() = 0;
343         virtual status_t      cancelAutoFocus() = 0;
344         virtual status_t      takePicture(int msgType) = 0;
345         virtual status_t      setParameters(const String8& params) = 0;
346         virtual String8       getParameters() const = 0;
347         virtual status_t      sendCommand(int32_t cmd, int32_t arg1, int32_t arg2) = 0;
348         virtual status_t      setVideoTarget(const sp<IGraphicBufferProducer>& bufferProducer) = 0;
349 
350         // Interface used by CameraService
351         Client(const sp<CameraService>& cameraService,
352                 const sp<hardware::ICameraClient>& cameraClient,
353                 const String16& clientPackageName,
354                 const String8& cameraIdStr,
355                 int api1CameraId,
356                 int cameraFacing,
357                 int clientPid,
358                 uid_t clientUid,
359                 int servicePid);
360         ~Client();
361 
362         // return our camera client
getRemoteCallback()363         const sp<hardware::ICameraClient>&    getRemoteCallback() {
364             return mRemoteCallback;
365         }
366 
asBinderWrapper()367         virtual sp<IBinder> asBinderWrapper() {
368             return asBinder(this);
369         }
370 
371         virtual void         notifyError(int32_t errorCode,
372                                          const CaptureResultExtras& resultExtras);
373 
374         // Check what API level is used for this client. This is used to determine which
375         // superclass this can be cast to.
376         virtual bool canCastToApiClient(apiLevel level) const;
377     protected:
378         // Initialized in constructor
379 
380         // - The app-side Binder interface to receive callbacks from us
381         sp<hardware::ICameraClient>               mRemoteCallback;
382 
383         int mCameraId;  // All API1 clients use integer camera IDs
384     }; // class Client
385 
386     /**
387      * A listener class that implements the LISTENER interface for use with a ClientManager, and
388      * implements the following methods:
389      *    void onClientRemoved(const ClientDescriptor<KEY, VALUE>& descriptor);
390      *    void onClientAdded(const ClientDescriptor<KEY, VALUE>& descriptor);
391      */
392     class ClientEventListener {
393     public:
394         void onClientAdded(const resource_policy::ClientDescriptor<String8,
395                 sp<CameraService::BasicClient>>& descriptor);
396         void onClientRemoved(const resource_policy::ClientDescriptor<String8,
397                 sp<CameraService::BasicClient>>& descriptor);
398     }; // class ClientEventListener
399 
400     typedef std::shared_ptr<resource_policy::ClientDescriptor<String8,
401             sp<CameraService::BasicClient>>> DescriptorPtr;
402 
403     /**
404      * A container class for managing active camera clients that are using HAL devices.  Active
405      * clients are represented by ClientDescriptor objects that contain strong pointers to the
406      * actual BasicClient subclass binder interface implementation.
407      *
408      * This class manages the eviction behavior for the camera clients.  See the parent class
409      * implementation in utils/ClientManager for the specifics of this behavior.
410      */
411     class CameraClientManager : public resource_policy::ClientManager<String8,
412             sp<CameraService::BasicClient>, ClientEventListener> {
413     public:
414         CameraClientManager();
415         virtual ~CameraClientManager();
416 
417         /**
418          * Return a strong pointer to the active BasicClient for this camera ID, or an empty
419          * if none exists.
420          */
421         sp<CameraService::BasicClient> getCameraClient(const String8& id) const;
422 
423         /**
424          * Return a string describing the current state.
425          */
426         String8 toString() const;
427 
428         /**
429          * Make a ClientDescriptor object wrapping the given BasicClient strong pointer.
430          */
431         static DescriptorPtr makeClientDescriptor(const String8& key, const sp<BasicClient>& value,
432                 int32_t cost, const std::set<String8>& conflictingKeys, int32_t score,
433                 int32_t ownerId, int32_t state);
434 
435         /**
436          * Make a ClientDescriptor object wrapping the given BasicClient strong pointer with
437          * values intialized from a prior ClientDescriptor.
438          */
439         static DescriptorPtr makeClientDescriptor(const sp<BasicClient>& value,
440                 const CameraService::DescriptorPtr& partial);
441 
442     }; // class CameraClientManager
443 
444 private:
445 
446     typedef hardware::camera::common::V1_0::CameraDeviceStatus CameraDeviceStatus;
447 
448     /**
449      * Typesafe version of device status, containing both the HAL-layer and the service interface-
450      * layer values.
451      */
452     enum class StatusInternal : int32_t {
453         NOT_PRESENT = static_cast<int32_t>(CameraDeviceStatus::NOT_PRESENT),
454         PRESENT = static_cast<int32_t>(CameraDeviceStatus::PRESENT),
455         ENUMERATING = static_cast<int32_t>(CameraDeviceStatus::ENUMERATING),
456         NOT_AVAILABLE = static_cast<int32_t>(hardware::ICameraServiceListener::STATUS_NOT_AVAILABLE),
457         UNKNOWN = static_cast<int32_t>(hardware::ICameraServiceListener::STATUS_UNKNOWN)
458     };
459 
460     /**
461      * Container class for the state of each logical camera device, including: ID, status, and
462      * dependencies on other devices.  The mapping of camera ID -> state saved in mCameraStates
463      * represents the camera devices advertised by the HAL (and any USB devices, when we add
464      * those).
465      *
466      * This container does NOT represent an active camera client.  These are represented using
467      * the ClientDescriptors stored in mActiveClientManager.
468      */
469     class CameraState {
470     public:
471 
472         /**
473          * Make a new CameraState and set the ID, cost, and conflicting devices using the values
474          * returned in the HAL's camera_info struct for each device.
475          */
476         CameraState(const String8& id, int cost, const std::set<String8>& conflicting,
477                 bool isHidden);
478         virtual ~CameraState();
479 
480         /**
481          * Return the status for this device.
482          *
483          * This method acquires mStatusLock.
484          */
485         StatusInternal getStatus() const;
486 
487         /**
488          * This function updates the status for this camera device, unless the given status
489          * is in the given list of rejected status states, and execute the function passed in
490          * with a signature onStatusUpdateLocked(const String8&, int32_t)
491          * if the status has changed.
492          *
493          * This method is idempotent, and will not result in the function passed to
494          * onStatusUpdateLocked being called more than once for the same arguments.
495          * This method aquires mStatusLock.
496          */
497         template<class Func>
498         void updateStatus(StatusInternal status,
499                 const String8& cameraId,
500                 std::initializer_list<StatusInternal> rejectSourceStates,
501                 Func onStatusUpdatedLocked);
502 
503         /**
504          * Return the last set CameraParameters object generated from the information returned by
505          * the HAL for this device (or an empty CameraParameters object if none has been set).
506          */
507         CameraParameters getShimParams() const;
508 
509         /**
510          * Set the CameraParameters for this device.
511          */
512         void setShimParams(const CameraParameters& params);
513 
514         /**
515          * Return the resource_cost advertised by the HAL for this device.
516          */
517         int getCost() const;
518 
519         /**
520          * Return a set of the IDs of conflicting devices advertised by the HAL for this device.
521          */
522         std::set<String8> getConflicting() const;
523 
524         /**
525          * Return the ID of this camera device.
526          */
527         String8 getId() const;
528 
529         /**
530          * Return if the camera device is a publically hidden secure camera
531          */
532         bool isPublicallyHiddenSecureCamera() const;
533 
534     private:
535         const String8 mId;
536         StatusInternal mStatus; // protected by mStatusLock
537         const int mCost;
538         std::set<String8> mConflicting;
539         mutable Mutex mStatusLock;
540         CameraParameters mShimParams;
541         const bool mIsPublicallyHiddenSecureCamera;
542     }; // class CameraState
543 
544     // Observer for UID lifecycle enforcing that UIDs in idle
545     // state cannot use the camera to protect user privacy.
546     class UidPolicy : public BnUidObserver, public virtual IBinder::DeathRecipient {
547     public:
UidPolicy(sp<CameraService> service)548         explicit UidPolicy(sp<CameraService> service)
549                 : mRegistered(false), mService(service) {}
550 
551         void registerSelf();
552         void unregisterSelf();
553 
554         bool isUidActive(uid_t uid, String16 callingPackage);
555         int32_t getProcState(uid_t uid);
556 
557         void onUidGone(uid_t uid, bool disabled);
558         void onUidActive(uid_t uid);
559         void onUidIdle(uid_t uid, bool disabled);
560         void onUidStateChanged(uid_t uid, int32_t procState, int64_t procStateSeq);
561 
562         void addOverrideUid(uid_t uid, String16 callingPackage, bool active);
563         void removeOverrideUid(uid_t uid, String16 callingPackage);
564 
565         void registerMonitorUid(uid_t uid);
566         void unregisterMonitorUid(uid_t uid);
567 
568         // IBinder::DeathRecipient implementation
569         virtual void binderDied(const wp<IBinder> &who);
570     private:
571         bool isUidActiveLocked(uid_t uid, String16 callingPackage);
572         int32_t getProcStateLocked(uid_t uid);
573         void updateOverrideUid(uid_t uid, String16 callingPackage, bool active, bool insert);
574 
575         Mutex mUidLock;
576         bool mRegistered;
577         ActivityManager mAm;
578         wp<CameraService> mService;
579         std::unordered_set<uid_t> mActiveUids;
580         // Monitored uid map to cached procState and refCount pair
581         std::unordered_map<uid_t, std::pair<int32_t, size_t>> mMonitoredUids;
582         std::unordered_map<uid_t, bool> mOverrideUids;
583     }; // class UidPolicy
584 
585     // If sensor privacy is enabled then all apps, including those that are active, should be
586     // prevented from accessing the camera.
587     class SensorPrivacyPolicy : public hardware::BnSensorPrivacyListener,
588             public virtual IBinder::DeathRecipient {
589         public:
SensorPrivacyPolicy(wp<CameraService> service)590             explicit SensorPrivacyPolicy(wp<CameraService> service)
591                     : mService(service), mSensorPrivacyEnabled(false), mRegistered(false) {}
592 
593             void registerSelf();
594             void unregisterSelf();
595 
596             bool isSensorPrivacyEnabled();
597 
598             binder::Status onSensorPrivacyChanged(bool enabled);
599 
600             // IBinder::DeathRecipient implementation
601             virtual void binderDied(const wp<IBinder> &who);
602 
603         private:
604             SensorPrivacyManager mSpm;
605             wp<CameraService> mService;
606             Mutex mSensorPrivacyLock;
607             bool mSensorPrivacyEnabled;
608             bool mRegistered;
609     };
610 
611     sp<UidPolicy> mUidPolicy;
612 
613     sp<SensorPrivacyPolicy> mSensorPrivacyPolicy;
614 
615     // Delay-load the Camera HAL module
616     virtual void onFirstRef();
617 
618     // Eumerate all camera providers in the system
619     status_t enumerateProviders();
620 
621     // Add/remove a new camera to camera and torch state lists or remove an unplugged one
622     // Caller must not hold mServiceLock
623     void addStates(const String8 id);
624     void removeStates(const String8 id);
625 
626     // Check if we can connect, before we acquire the service lock.
627     // The returned originalClientPid is the PID of the original process that wants to connect to
628     // camera.
629     // The returned clientPid is the PID of the client that directly connects to camera.
630     // originalClientPid and clientPid are usually the same except when the application uses
631     // mediaserver to connect to camera (using MediaRecorder to connect to camera). In that case,
632     // clientPid is the PID of mediaserver and originalClientPid is the PID of the application.
633     binder::Status validateConnectLocked(const String8& cameraId, const String8& clientName8,
634             /*inout*/int& clientUid, /*inout*/int& clientPid, /*out*/int& originalClientPid) const;
635     binder::Status validateClientPermissionsLocked(const String8& cameraId, const String8& clientName8,
636             /*inout*/int& clientUid, /*inout*/int& clientPid, /*out*/int& originalClientPid) const;
637 
638     // Handle active client evictions, and update service state.
639     // Only call with with mServiceLock held.
640     status_t handleEvictionsLocked(const String8& cameraId, int clientPid,
641         apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
642         /*out*/
643         sp<BasicClient>* client,
644         std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial);
645 
646     // Should an operation attempt on a cameraId be rejected, if the camera id is
647     // advertised as a publically hidden secure camera, by the camera HAL ?
648     bool shouldRejectHiddenCameraConnection(const String8& cameraId);
649 
650     bool isPublicallyHiddenSecureCamera(const String8& cameraId);
651 
652     // Single implementation shared between the various connect calls
653     template<class CALLBACK, class CLIENT>
654     binder::Status connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
655             int api1CameraId, int halVersion, const String16& clientPackageName,
656             int clientUid, int clientPid, apiLevel effectiveApiLevel, bool shimUpdateOnly,
657             /*out*/sp<CLIENT>& device);
658 
659     // Lock guarding camera service state
660     Mutex               mServiceLock;
661 
662     // Condition to use with mServiceLock, used to handle simultaneous connect calls from clients
663     std::shared_ptr<WaitableMutexWrapper> mServiceLockWrapper;
664 
665     // Return NO_ERROR if the device with a give ID can be connected to
666     status_t checkIfDeviceIsUsable(const String8& cameraId) const;
667 
668     // Container for managing currently active application-layer clients
669     CameraClientManager mActiveClientManager;
670 
671     // Mapping from camera ID -> state for each device, map is protected by mCameraStatesLock
672     std::map<String8, std::shared_ptr<CameraState>> mCameraStates;
673 
674     // Mutex guarding mCameraStates map
675     mutable Mutex mCameraStatesLock;
676 
677     // Circular buffer for storing event logging for dumps
678     RingBuffer<String8> mEventLog;
679     Mutex mLogLock;
680 
681     // The last monitored tags set by client
682     String8 mMonitorTags;
683 
684     // Currently allowed user IDs
685     std::set<userid_t> mAllowedUsers;
686 
687     /**
688      * Get the camera state for a given camera id.
689      *
690      * This acquires mCameraStatesLock.
691      */
692     std::shared_ptr<CameraService::CameraState> getCameraState(const String8& cameraId) const;
693 
694     /**
695      * Evict client who's remote binder has died.  Returns true if this client was in the active
696      * list and was disconnected.
697      *
698      * This method acquires mServiceLock.
699      */
700     bool evictClientIdByRemote(const wp<IBinder>& cameraClient);
701 
702     /**
703      * Remove the given client from the active clients list; does not disconnect the client.
704      *
705      * This method acquires mServiceLock.
706      */
707     void removeByClient(const BasicClient* client);
708 
709     /**
710      * Add new client to active clients list after conflicting clients have disconnected using the
711      * values set in the partial descriptor passed in to construct the actual client descriptor.
712      * This is typically called at the end of a connect call.
713      *
714      * This method must be called with mServiceLock held.
715      */
716     void finishConnectLocked(const sp<BasicClient>& client, const DescriptorPtr& desc);
717 
718     /**
719      * Returns the underlying camera Id string mapped to a camera id int
720      * Empty string is returned when the cameraIdInt is invalid.
721      */
722     String8 cameraIdIntToStr(int cameraIdInt);
723 
724     /**
725      * Returns the underlying camera Id string mapped to a camera id int
726      * Empty string is returned when the cameraIdInt is invalid.
727      */
728     std::string cameraIdIntToStrLocked(int cameraIdInt);
729 
730     /**
731      * Remove a single client corresponding to the given camera id from the list of active clients.
732      * If none exists, return an empty strongpointer.
733      *
734      * This method must be called with mServiceLock held.
735      */
736     sp<CameraService::BasicClient> removeClientLocked(const String8& cameraId);
737 
738     /**
739      * Handle a notification that the current device user has changed.
740      */
741     void doUserSwitch(const std::vector<int32_t>& newUserIds);
742 
743     /**
744      * Add an event log message.
745      */
746     void logEvent(const char* event);
747 
748     /**
749      * Add an event log message that a client has been disconnected.
750      */
751     void logDisconnected(const char* cameraId, int clientPid, const char* clientPackage);
752 
753     /**
754      * Add an event log message that a client has been connected.
755      */
756     void logConnected(const char* cameraId, int clientPid, const char* clientPackage);
757 
758     /**
759      * Add an event log message that a client's connect attempt has been rejected.
760      */
761     void logRejected(const char* cameraId, int clientPid, const char* clientPackage,
762             const char* reason);
763 
764     /**
765      * Add an event log message when a client calls setTorchMode succesfully.
766      */
767     void logTorchEvent(const char* cameraId, const char *torchState, int clientPid);
768 
769     /**
770      * Add an event log message that the current device user has been switched.
771      */
772     void logUserSwitch(const std::set<userid_t>& oldUserIds,
773         const std::set<userid_t>& newUserIds);
774 
775     /**
776      * Add an event log message that a device has been removed by the HAL
777      */
778     void logDeviceRemoved(const char* cameraId, const char* reason);
779 
780     /**
781      * Add an event log message that a device has been added by the HAL
782      */
783     void logDeviceAdded(const char* cameraId, const char* reason);
784 
785     /**
786      * Add an event log message that a client has unexpectedly died.
787      */
788     void logClientDied(int clientPid, const char* reason);
789 
790     /**
791      * Add a event log message that a serious service-level error has occured
792      * The errorCode should be one of the Android Errors
793      */
794     void logServiceError(const char* msg, int errorCode);
795 
796     /**
797      * Dump the event log to an FD
798      */
799     void dumpEventLog(int fd);
800 
801     /**
802      * This method will acquire mServiceLock
803      */
804     void updateCameraNumAndIds();
805 
806     int                 mNumberOfCameras;
807 
808     std::vector<std::string> mNormalDeviceIds;
809 
810     // sounds
811     sp<MediaPlayer>     newMediaPlayer(const char *file);
812 
813     Mutex               mSoundLock;
814     sp<MediaPlayer>     mSoundPlayer[NUM_SOUNDS];
815     int                 mSoundRef;  // reference count (release all MediaPlayer when 0)
816 
817     // Basic flag on whether the camera subsystem is in a usable state
818     bool                mInitialized;
819 
820     sp<CameraProviderManager> mCameraProviderManager;
821 
822     class ServiceListener : public virtual IBinder::DeathRecipient {
823         public:
ServiceListener(sp<CameraService> parent,sp<hardware::ICameraServiceListener> listener,int uid,int pid,bool openCloseCallbackAllowed)824             ServiceListener(sp<CameraService> parent, sp<hardware::ICameraServiceListener> listener,
825                     int uid, int pid, bool openCloseCallbackAllowed) : mParent(parent),
826                     mListener(listener), mListenerUid(uid), mListenerPid(pid),
827                     mOpenCloseCallbackAllowed(openCloseCallbackAllowed) {}
828 
initialize()829             status_t initialize() {
830                 return IInterface::asBinder(mListener)->linkToDeath(this);
831             }
832 
binderDied(const wp<IBinder> &)833             virtual void binderDied(const wp<IBinder> &/*who*/) {
834                 auto parent = mParent.promote();
835                 if (parent.get() != nullptr) {
836                     parent->removeListener(mListener);
837                 }
838             }
839 
getListenerUid()840             int getListenerUid() { return mListenerUid; }
getListenerPid()841             int getListenerPid() { return mListenerPid; }
getListener()842             sp<hardware::ICameraServiceListener> getListener() { return mListener; }
isOpenCloseCallbackAllowed()843             bool isOpenCloseCallbackAllowed() { return mOpenCloseCallbackAllowed; }
844 
845         private:
846             wp<CameraService> mParent;
847             sp<hardware::ICameraServiceListener> mListener;
848             int mListenerUid;
849             int mListenerPid;
850             bool mOpenCloseCallbackAllowed = false;
851     };
852 
853     // Guarded by mStatusListenerMutex
854     std::vector<std::pair<bool, sp<ServiceListener>>> mListenerList;
855 
856     Mutex       mStatusListenerLock;
857 
858     /**
859      * Update the status for the given camera id (if that device exists), and broadcast the
860      * status update to all current ICameraServiceListeners if the status has changed.  Any
861      * statuses in rejectedSourceStates will be ignored.
862      *
863      * This method must be idempotent.
864      * This method acquires mStatusLock and mStatusListenerLock.
865      */
866     void updateStatus(StatusInternal status,
867             const String8& cameraId,
868             std::initializer_list<StatusInternal>
869                 rejectedSourceStates);
870     void updateStatus(StatusInternal status,
871             const String8& cameraId);
872 
873     /**
874      * Update the opened/closed status of the given camera id.
875      *
876      * This method acqiures mStatusListenerLock.
877      */
878     void updateOpenCloseStatus(const String8& cameraId, bool open, const String16& packageName);
879 
880     // flashlight control
881     sp<CameraFlashlight> mFlashlight;
882     // guard mTorchStatusMap
883     Mutex                mTorchStatusMutex;
884     // guard mTorchClientMap
885     Mutex                mTorchClientMapMutex;
886     // guard mTorchUidMap
887     Mutex                mTorchUidMapMutex;
888     // camera id -> torch status
889     KeyedVector<String8, hardware::camera::common::V1_0::TorchModeStatus>
890             mTorchStatusMap;
891     // camera id -> torch client binder
892     // only store the last client that turns on each camera's torch mode
893     KeyedVector<String8, sp<IBinder>> mTorchClientMap;
894     // camera id -> [incoming uid, current uid] pair
895     std::map<String8, std::pair<int, int>> mTorchUidMap;
896 
897     // check and handle if torch client's process has died
898     void handleTorchClientBinderDied(const wp<IBinder> &who);
899 
900     // handle torch mode status change and invoke callbacks. mTorchStatusMutex
901     // should be locked.
902     void onTorchStatusChangedLocked(const String8& cameraId,
903             hardware::camera::common::V1_0::TorchModeStatus newStatus);
904 
905     // get a camera's torch status. mTorchStatusMutex should be locked.
906     status_t getTorchStatusLocked(const String8 &cameraId,
907              hardware::camera::common::V1_0::TorchModeStatus *status) const;
908 
909     // set a camera's torch status. mTorchStatusMutex should be locked.
910     status_t setTorchStatusLocked(const String8 &cameraId,
911             hardware::camera::common::V1_0::TorchModeStatus status);
912 
913     // IBinder::DeathRecipient implementation
914     virtual void        binderDied(const wp<IBinder> &who);
915 
916     /**
917      * Initialize and cache the metadata used by the HAL1 shim for a given cameraId.
918      *
919      * Sets Status to a service-specific error on failure
920      */
921     binder::Status      initializeShimMetadata(int cameraId);
922 
923     /**
924      * Get the cached CameraParameters for the camera. If they haven't been
925      * cached yet, then initialize them for the first time.
926      *
927      * Sets Status to a service-specific error on failure
928      */
929     binder::Status      getLegacyParametersLazy(int cameraId, /*out*/CameraParameters* parameters);
930 
931     // Blocks all clients from the UID
932     void blockClientsForUid(uid_t uid);
933 
934     // Blocks all active clients.
935     void blockAllClients();
936 
937     // Overrides the UID state as if it is idle
938     status_t handleSetUidState(const Vector<String16>& args, int err);
939 
940     // Clears the override for the UID state
941     status_t handleResetUidState(const Vector<String16>& args, int err);
942 
943     // Gets the UID state
944     status_t handleGetUidState(const Vector<String16>& args, int out, int err);
945 
946     // Prints the shell command help
947     status_t printHelp(int out);
948 
949     /**
950      * Get the current system time as a formatted string.
951      */
952     static String8 getFormattedCurrentTime();
953 
954     static binder::Status makeClient(const sp<CameraService>& cameraService,
955             const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId,
956             int api1CameraId, int facing, int clientPid, uid_t clientUid, int servicePid,
957             int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
958             /*out*/sp<BasicClient>* client);
959 
960     status_t checkCameraAccess(const String16& opPackageName);
961 
962     static String8 toString(std::set<userid_t> intSet);
963     static int32_t mapToInterface(hardware::camera::common::V1_0::TorchModeStatus status);
964     static StatusInternal mapToInternal(hardware::camera::common::V1_0::CameraDeviceStatus status);
965     static int32_t mapToInterface(StatusInternal status);
966 
967     // Guard mCameraServiceProxy
968     static Mutex sProxyMutex;
969     // Cached interface to the camera service proxy in system service
970     static sp<hardware::ICameraServiceProxy> sCameraServiceProxy;
971 
972     static sp<hardware::ICameraServiceProxy> getCameraServiceProxy();
973     static void pingCameraServiceProxy();
974 
975     void broadcastTorchModeStatus(const String8& cameraId,
976             hardware::camera::common::V1_0::TorchModeStatus status);
977 };
978 
979 } // namespace android
980 
981 #endif
982