• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/content/AttributionSourceState.h>
21 #include <android/hardware/BnCameraService.h>
22 #include <android/hardware/BnSensorPrivacyListener.h>
23 #include <android/hardware/ICameraServiceListener.h>
24 #include <android/hardware/camera2/BnCameraInjectionSession.h>
25 #include <android/hardware/camera2/ICameraInjectionCallback.h>
26 
27 #include <cutils/multiuser.h>
28 #include <utils/Vector.h>
29 #include <utils/KeyedVector.h>
30 #include <binder/ActivityManager.h>
31 #include <binder/AppOpsManager.h>
32 #include <binder/BinderService.h>
33 #include <binder/IServiceManager.h>
34 #include <binder/IActivityManager.h>
35 #include <binder/IAppOpsCallback.h>
36 #include <binder/IPermissionController.h>
37 #include <binder/IUidObserver.h>
38 #include <hardware/camera.h>
39 #include <sensorprivacy/SensorPrivacyManager.h>
40 
41 #include <android/hardware/camera/common/1.0/types.h>
42 
43 #include <camera/VendorTagDescriptor.h>
44 #include <camera/CaptureResult.h>
45 #include <camera/CameraParameters.h>
46 #include <camera/camera2/ConcurrentCamera.h>
47 
48 #include "CameraFlashlight.h"
49 
50 #include "common/CameraProviderManager.h"
51 #include "media/RingBuffer.h"
52 #include "utils/AutoConditionLock.h"
53 #include "utils/ClientManager.h"
54 #include "utils/IPCTransport.h"
55 #include "utils/CameraServiceProxyWrapper.h"
56 #include "utils/AttributionAndPermissionUtils.h"
57 #include "utils/VirtualDeviceCameraIdMapper.h"
58 
59 #include <set>
60 #include <string>
61 #include <list>
62 #include <map>
63 #include <memory>
64 #include <mutex>
65 #include <optional>
66 #include <utility>
67 #include <unordered_map>
68 #include <unordered_set>
69 #include <vector>
70 
71 namespace android {
72 
73 extern volatile int32_t gLogLevel;
74 
75 class MemoryHeapBase;
76 class MediaPlayer;
77 
78 class CameraService :
79     public BinderService<CameraService>,
80     public virtual ::android::hardware::BnCameraService,
81     public virtual IBinder::DeathRecipient,
82     public virtual CameraProviderManager::StatusListener,
83     public virtual IServiceManager::LocalRegistrationCallback,
84     public AttributionAndPermissionUtilsEncapsulator
85 {
86     friend class BinderService<CameraService>;
87     friend class CameraOfflineSessionClient;
88 public:
89     class Client;
90     class BasicClient;
91     class OfflineClient;
92 
93     // The effective API level.  The Camera2 API running in LEGACY mode counts as API_1.
94     enum apiLevel {
95         API_1 = 1,
96         API_2 = 2
97     };
98 
99     // 3 second busy timeout when other clients are connecting
100     static const nsecs_t DEFAULT_CONNECT_TIMEOUT_NS = 3000000000;
101 
102     // 1 second busy timeout when other clients are disconnecting
103     static const nsecs_t DEFAULT_DISCONNECT_TIMEOUT_NS = 1000000000;
104 
105     // Default number of messages to store in eviction log
106     static const size_t DEFAULT_EVENT_LOG_LENGTH = 100;
107 
108     // Event log ID
109     static const int SN_EVENT_LOG_ID = 0x534e4554;
110 
111     // Keep this in sync with frameworks/base/core/java/android/os/UserHandle.java
112     static const userid_t USER_SYSTEM = 0;
113 
114     // Register camera service
115     static void instantiate();
116 
117     // Implementation of BinderService<T>
getServiceName()118     static char const* getServiceName() { return "media.camera"; }
119 
120     // Implementation of IServiceManager::LocalRegistrationCallback
121     virtual void onServiceRegistration(const String16& name, const sp<IBinder>& binder) override;
122 
123                         // Non-null arguments for cameraServiceProxyWrapper should be provided for
124                         // testing purposes only.
125                         CameraService(std::shared_ptr<CameraServiceProxyWrapper>
126                                 cameraServiceProxyWrapper = nullptr,
127                                 std::shared_ptr<AttributionAndPermissionUtils>
128                                 attributionAndPermissionUtils = nullptr);
129     virtual             ~CameraService();
130 
131     /////////////////////////////////////////////////////////////////////
132     // HAL Callbacks - implements CameraProviderManager::StatusListener
133 
134     virtual void        onDeviceStatusChanged(const std::string &cameraId,
135             CameraDeviceStatus newHalStatus) override;
136     virtual void        onDeviceStatusChanged(const std::string &cameraId,
137             const std::string &physicalCameraId,
138             CameraDeviceStatus newHalStatus) override;
139     // This method may hold CameraProviderManager::mInterfaceMutex as a part
140     // of calling getSystemCameraKind() internally. Care should be taken not to
141     // directly / indirectly call this from callers who also hold
142     // mInterfaceMutex.
143     virtual void        onTorchStatusChanged(const std::string& cameraId,
144             TorchModeStatus newStatus) override;
145     // Does not hold CameraProviderManager::mInterfaceMutex.
146     virtual void        onTorchStatusChanged(const std::string& cameraId,
147             TorchModeStatus newStatus,
148             SystemCameraKind kind) override;
149     virtual void        onNewProviderRegistered() override;
150 
151     /////////////////////////////////////////////////////////////////////
152     // ICameraService
153     // IMPORTANT: All binder calls that deal with logicalCameraId should use
154     // resolveCameraId(logicalCameraId, deviceId, devicePolicy) to arrive at the correct
155     // cameraId to perform the operation on (in case of contexts
156     // associated with virtual devices).
157     virtual binder::Status     getNumberOfCameras(int32_t type, int32_t deviceId,
158             int32_t devicePolicy, int32_t* numCameras);
159 
160     virtual binder::Status     getCameraInfo(int cameraId, int rotationOverride,
161             int32_t deviceId, int32_t devicePolicy, hardware::CameraInfo* cameraInfo) override;
162     virtual binder::Status     getCameraCharacteristics(const std::string& cameraId,
163             int targetSdkVersion, int rotationOverride, int32_t deviceId,
164             int32_t devicePolicy, CameraMetadata* cameraInfo) override;
165     virtual binder::Status     getCameraVendorTagDescriptor(
166             /*out*/
167             hardware::camera2::params::VendorTagDescriptor* desc);
168     virtual binder::Status     getCameraVendorTagCache(
169             /*out*/
170             hardware::camera2::params::VendorTagDescriptorCache* cache);
171 
172     virtual binder::Status     connect(const sp<hardware::ICameraClient>& cameraClient,
173             int32_t cameraId, const std::string& clientPackageName,
174             int32_t clientUid, int clientPid, int targetSdkVersion,
175             int rotationOverride, bool forceSlowJpegMode, int32_t deviceId,
176             int32_t devicePolicy, /*out*/ sp<hardware::ICamera>* device) override;
177 
178     virtual binder::Status     connectDevice(
179             const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
180             const std::string& cameraId,
181             const std::string& clientPackageName, const std::optional<std::string>& clientFeatureId,
182             int32_t clientUid, int scoreOffset, int targetSdkVersion, int rotationOverride,
183             int32_t deviceId, int32_t devicePolicy,
184             /*out*/
185             sp<hardware::camera2::ICameraDeviceUser>* device);
186 
187     virtual binder::Status    addListener(const sp<hardware::ICameraServiceListener>& listener,
188             /*out*/
189             std::vector<hardware::CameraStatus>* cameraStatuses);
190     virtual binder::Status    removeListener(
191             const sp<hardware::ICameraServiceListener>& listener);
192 
193     virtual binder::Status getConcurrentCameraIds(
194         /*out*/
195         std::vector<hardware::camera2::utils::ConcurrentCameraIdCombination>* concurrentCameraIds);
196 
197     virtual binder::Status isConcurrentSessionConfigurationSupported(
198         const std::vector<hardware::camera2::utils::CameraIdAndSessionConfiguration>& sessions,
199         int targetSdkVersion, int32_t deviceId, int32_t devicePolicy,
200         /*out*/bool* supported);
201 
202     virtual binder::Status    getLegacyParameters(
203             int32_t cameraId,
204             /*out*/
205             std::string* parameters);
206 
207     virtual binder::Status    setTorchMode(const std::string& cameraId, bool enabled,
208             const sp<IBinder>& clientBinder, int32_t deviceId, int32_t devicePolicy);
209 
210     virtual binder::Status    turnOnTorchWithStrengthLevel(const std::string& cameraId,
211             int32_t torchStrength, const sp<IBinder>& clientBinder, int32_t deviceId,
212             int32_t devicePolicy);
213 
214     virtual binder::Status    getTorchStrengthLevel(const std::string& cameraId, int32_t deviceId,
215             int32_t devicePolicy, int32_t* torchStrength);
216 
217     virtual binder::Status    notifySystemEvent(int32_t eventId,
218             const std::vector<int32_t>& args);
219 
220     virtual binder::Status    notifyDeviceStateChange(int64_t newState);
221 
222     virtual binder::Status    notifyDisplayConfigurationChange();
223 
224     // OK = supports api of that version, -EOPNOTSUPP = does not support
225     virtual binder::Status    supportsCameraApi(
226             const std::string& cameraId, int32_t apiVersion,
227             /*out*/
228             bool *isSupported);
229 
230     virtual binder::Status    isHiddenPhysicalCamera(
231             const std::string& cameraId,
232             /*out*/
233             bool *isSupported);
234 
235     virtual binder::Status injectCamera(
236             const std::string& packageName, const std::string& internalCamId,
237             const std::string& externalCamId,
238             const sp<hardware::camera2::ICameraInjectionCallback>& callback,
239             /*out*/
240             sp<hardware::camera2::ICameraInjectionSession>* cameraInjectionSession);
241 
242     virtual binder::Status reportExtensionSessionStats(
243             const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/);
244 
245     virtual binder::Status injectSessionParams(
246             const std::string& cameraId,
247             const hardware::camera2::impl::CameraMetadataNative& sessionParams);
248 
249     virtual binder::Status createDefaultRequest(const std::string& cameraId, int templateId,
250             int32_t deviceId, int32_t devicePolicy,
251             /*out*/
252             hardware::camera2::impl::CameraMetadataNative* request);
253 
254     virtual binder::Status isSessionConfigurationWithParametersSupported(
255             const std::string& cameraId, int targetSdkVersion,
256             const SessionConfiguration& sessionConfiguration,
257             int32_t deviceId, int32_t devicePolicy,
258             /*out*/ bool* supported);
259 
260     virtual binder::Status getSessionCharacteristics(
261             const std::string& cameraId, int targetSdkVersion, int rotationOverride,
262             const SessionConfiguration& sessionConfiguration, int32_t deviceId,
263             int32_t devicePolicy, /*out*/ CameraMetadata* outMetadata);
264 
265     // Extra permissions checks
266     virtual status_t    onTransact(uint32_t code, const Parcel& data,
267                                    Parcel* reply, uint32_t flags);
268 
269     virtual status_t    dump(int fd, const Vector<String16>& args);
270 
271     virtual status_t    shellCommand(int in, int out, int err, const Vector<String16>& args);
272 
273     binder::Status      addListenerHelper(const sp<hardware::ICameraServiceListener>& listener,
274             /*out*/
275             std::vector<hardware::CameraStatus>* cameraStatuses, bool isVendor = false,
276             bool isProcessLocalTest = false);
277 
278     // Monitored UIDs availability notification
279     void                notifyMonitoredUids();
280     void                notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet);
281 
282     // Stores current open session device info in temp file.
283     void cacheDump();
284 
285     // Register an offline client for a given active camera id
286     status_t addOfflineClient(const std::string &cameraId, sp<BasicClient> offlineClient);
287 
288     /////////////////////////////////////////////////////////////////////
289     // Client functionality
290 
291     enum sound_kind {
292         SOUND_SHUTTER = 0,
293         SOUND_RECORDING_START = 1,
294         SOUND_RECORDING_STOP = 2,
295         NUM_SOUNDS
296     };
297 
298     void                playSound(sound_kind kind);
299     void                loadSoundLocked(sound_kind kind);
300     void                decreaseSoundRef();
301     void                increaseSoundRef();
302 
303     /////////////////////////////////////////////////////////////////////
304     // CameraDeviceFactory functionality
305     std::pair<int, IPCTransport>    getDeviceVersion(const std::string& cameraId,
306             int rotationOverride,
307             int* portraitRotation,
308             int* facing = nullptr, int* orientation = nullptr);
309 
310     /////////////////////////////////////////////////////////////////////
311     // Methods to be used in CameraService class tests only
312     //
313     // CameraService class test method only - clear static variables in the
314     // cameraserver process, which otherwise might affect multiple test runs.
315     void                clearCachedVariables();
316 
317     // Add test listener, linkToDeath won't be called since this is for process
318     // local testing.
319     binder::Status    addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
320             /*out*/
321             std::vector<hardware::CameraStatus>* cameraStatuses);
322 
323     /////////////////////////////////////////////////////////////////////
324     // Shared utilities
325     static binder::Status filterGetInfoErrorCode(status_t err);
326 
327     /**
328      * Returns true if the device is an automotive device and cameraId is system
329      * only camera which has characteristic AUTOMOTIVE_LOCATION value as either
330      * AUTOMOTIVE_LOCATION_EXTERIOR_LEFT,AUTOMOTIVE_LOCATION_EXTERIOR_RIGHT,
331      * AUTOMOTIVE_LOCATION_EXTERIOR_FRONT or AUTOMOTIVE_LOCATION_EXTERIOR_REAR.
332      */
333     bool isAutomotiveExteriorSystemCamera(const std::string& cameraId) const;
334 
335     /////////////////////////////////////////////////////////////////////
336     // CameraClient functionality
337 
338     class BasicClient :
339         public virtual RefBase,
340         public AttributionAndPermissionUtilsEncapsulator {
341     friend class CameraService;
342     public:
343         virtual status_t       initialize(sp<CameraProviderManager> manager,
344                 const std::string& monitorTags) = 0;
345         virtual binder::Status disconnect();
346 
347         // because we can't virtually inherit IInterface, which breaks
348         // virtual inheritance
349         virtual sp<IBinder>    asBinderWrapper() = 0;
350 
351         // Return the remote callback binder object (e.g. ICameraDeviceCallbacks)
getRemote()352         sp<IBinder>            getRemote() {
353             return mRemoteBinder;
354         }
355 
getOverrideToPortrait()356         bool getOverrideToPortrait() const {
357             return mRotationOverride == ICameraService::ROTATION_OVERRIDE_OVERRIDE_TO_PORTRAIT;
358         }
359 
360         // Disallows dumping over binder interface
361         virtual status_t dump(int fd, const Vector<String16>& args);
362         // Internal dump method to be called by CameraService
363         virtual status_t dumpClient(int fd, const Vector<String16>& args) = 0;
364 
365         virtual status_t startWatchingTags(const std::string &tags, int outFd);
366         virtual status_t stopWatchingTags(int outFd);
367         virtual status_t dumpWatchedEventsToVector(std::vector<std::string> &out);
368 
369         // Return the package name for this client
370         virtual std::string getPackageName() const;
371 
372         // Return the camera facing for this client
373         virtual int getCameraFacing() const;
374 
375         // Return the camera orientation for this client
376         virtual int getCameraOrientation() const;
377 
378         // Notify client about a fatal error
379         virtual void notifyError(int32_t errorCode,
380                 const CaptureResultExtras& resultExtras) = 0;
381 
382         // Get the UID of the application client using this
383         virtual uid_t getClientUid() const;
384 
385         // Get the PID of the application client using this
386         virtual int getClientPid() const;
387 
388         // Check what API level is used for this client. This is used to determine which
389         // superclass this can be cast to.
390         virtual bool canCastToApiClient(apiLevel level) const;
391 
392         // Block the client form using the camera
393         virtual void block();
394 
395         // set audio restriction from client
396         // Will call into camera service and hold mServiceLock
397         virtual status_t setAudioRestriction(int32_t mode);
398 
399         // Get current global audio restriction setting
400         // Will call into camera service and hold mServiceLock
401         virtual int32_t getServiceAudioRestriction() const;
402 
403         // Get current audio restriction setting for this client
404         virtual int32_t getAudioRestriction() const;
405 
406         static bool isValidAudioRestriction(int32_t mode);
407 
408         // Override rotate-and-crop AUTO behavior
409         virtual status_t setRotateAndCropOverride(uint8_t rotateAndCrop, bool fromHal = false) = 0;
410 
411         // Override autoframing AUTO behaviour
412         virtual status_t setAutoframingOverride(uint8_t autoframingValue) = 0;
413 
414         // Whether the client supports camera muting (black only output)
415         virtual bool supportsCameraMute() = 0;
416 
417         // Set/reset camera mute
418         virtual status_t setCameraMute(bool enabled) = 0;
419 
420         // Set Camera service watchdog
421         virtual status_t setCameraServiceWatchdog(bool enabled) = 0;
422 
423         // Set stream use case overrides
424         virtual void setStreamUseCaseOverrides(
425                 const std::vector<int64_t>& useCaseOverrides) = 0;
426 
427         // Clear stream use case overrides
428         virtual void clearStreamUseCaseOverrides() = 0;
429 
430         // Whether the client supports camera zoom override
431         virtual bool supportsZoomOverride() = 0;
432 
433         // Set/reset zoom override
434         virtual status_t setZoomOverride(int32_t zoomOverride) = 0;
435 
436         // The injection camera session to replace the internal camera
437         // session.
438         virtual status_t injectCamera(const std::string& injectedCamId,
439                 sp<CameraProviderManager> manager) = 0;
440 
441         // Stop the injection camera and restore to internal camera session.
442         virtual status_t stopInjection() = 0;
443 
444         // Inject session parameters into an existing session.
445         virtual status_t injectSessionParams(
446                 const hardware::camera2::impl::CameraMetadataNative& sessionParams) = 0;
447 
448     protected:
449         BasicClient(const sp<CameraService>& cameraService,
450                 const sp<IBinder>& remoteCallback,
451                 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
452                 const std::string& clientPackageName,
453                 bool nativeClient,
454                 const std::optional<std::string>& clientFeatureId,
455                 const std::string& cameraIdStr,
456                 int cameraFacing,
457                 int sensorOrientation,
458                 int clientPid,
459                 uid_t clientUid,
460                 int servicePid,
461                 int rotationOverride);
462 
463         virtual ~BasicClient();
464 
465         // the instance is in the middle of destruction. When this is set,
466         // the instance should not be accessed from callback.
467         // CameraService's mClientLock should be acquired to access this.
468         // - subclasses should set this to true in their destructors.
469         bool                            mDestructionStarted;
470 
471         // these are initialized in the constructor.
472         static sp<CameraService>        sCameraService;
473         const std::string               mCameraIdStr;
474         const int                       mCameraFacing;
475         const int                       mOrientation;
476         std::string                     mClientPackageName;
477         bool                            mSystemNativeClient;
478         std::optional<std::string>      mClientFeatureId;
479         pid_t                           mClientPid;
480         const uid_t                     mClientUid;
481         const pid_t                     mServicePid;
482         bool                            mDisconnected;
483         bool                            mUidIsTrusted;
484         int                             mRotationOverride;
485 
486         mutable Mutex                   mAudioRestrictionLock;
487         int32_t                         mAudioRestriction;
488 
489         // - The app-side Binder interface to receive callbacks from us
490         sp<IBinder>                     mRemoteBinder;   // immutable after constructor
491 
492         // Permissions management methods for camera lifecycle
493 
494         // Notify rest of system/apps about camera opening, and check appops
495         virtual status_t                startCameraOps();
496         // Notify rest of system/apps about camera starting to stream data, and confirm appops
497         virtual status_t                startCameraStreamingOps();
498         // Notify rest of system/apps about camera stopping streaming data
499         virtual status_t                finishCameraStreamingOps();
500         // Notify rest of system/apps about camera closing
501         virtual status_t                finishCameraOps();
502         // Handle errors for start/checkOps
503         virtual status_t                handleAppOpMode(int32_t mode);
504         // Just notify camera appops to trigger unblocking dialog if sensor
505         // privacy is enabled and camera mute is not supported
506         virtual status_t                noteAppOp();
507 
508         std::unique_ptr<AppOpsManager>  mAppOpsManager = nullptr;
509 
510         class OpsCallback : public BnAppOpsCallback {
511         public:
512             explicit OpsCallback(wp<BasicClient> client);
513             virtual void opChanged(int32_t op, const String16& packageName);
514 
515         private:
516             wp<BasicClient> mClient;
517 
518         }; // class OpsCallback
519 
520         sp<OpsCallback> mOpsCallback;
521         // Track whether checkOps was called successfully, to avoid
522         // finishing what we didn't start, on camera open.
523         bool            mOpsActive;
524         // Track whether startOps was called successfully on start of
525         // camera streaming.
526         bool            mOpsStreaming;
527 
528         // IAppOpsCallback interface, indirected through opListener
529         virtual void opChanged(int32_t op, const String16& packageName);
530     }; // class BasicClient
531 
532     class Client : public hardware::BnCamera, public BasicClient
533     {
534     public:
535         typedef hardware::ICameraClient TCamCallbacks;
536 
537         // ICamera interface (see ICamera for details)
538         virtual binder::Status disconnect();
539         virtual status_t      connect(const sp<hardware::ICameraClient>& client) = 0;
540         virtual status_t      lock() = 0;
541         virtual status_t      unlock() = 0;
542         virtual status_t      setPreviewTarget(const sp<IGraphicBufferProducer>& bufferProducer)=0;
543         virtual void          setPreviewCallbackFlag(int flag) = 0;
544         virtual status_t      setPreviewCallbackTarget(
545                 const sp<IGraphicBufferProducer>& callbackProducer) = 0;
546         virtual status_t      startPreview() = 0;
547         virtual void          stopPreview() = 0;
548         virtual bool          previewEnabled() = 0;
549         virtual status_t      setVideoBufferMode(int32_t videoBufferMode) = 0;
550         virtual status_t      startRecording() = 0;
551         virtual void          stopRecording() = 0;
552         virtual bool          recordingEnabled() = 0;
553         virtual void          releaseRecordingFrame(const sp<IMemory>& mem) = 0;
554         virtual status_t      autoFocus() = 0;
555         virtual status_t      cancelAutoFocus() = 0;
556         virtual status_t      takePicture(int msgType) = 0;
557         virtual status_t      setParameters(const String8& params) = 0;
558         virtual String8       getParameters() const = 0;
559         virtual status_t      sendCommand(int32_t cmd, int32_t arg1, int32_t arg2) = 0;
560         virtual status_t      setVideoTarget(const sp<IGraphicBufferProducer>& bufferProducer) = 0;
561 
562         // Interface used by CameraService
563         Client(const sp<CameraService>& cameraService,
564                 const sp<hardware::ICameraClient>& cameraClient,
565                 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
566                 const std::string& clientPackageName,
567                 bool systemNativeClient,
568                 const std::optional<std::string>& clientFeatureId,
569                 const std::string& cameraIdStr,
570                 int api1CameraId,
571                 int cameraFacing,
572                 int sensorOrientation,
573                 int clientPid,
574                 uid_t clientUid,
575                 int servicePid,
576                 int rotationOverride);
577         ~Client();
578 
579         // return our camera client
getRemoteCallback()580         const sp<hardware::ICameraClient>&    getRemoteCallback() {
581             return mRemoteCallback;
582         }
583 
asBinderWrapper()584         virtual sp<IBinder> asBinderWrapper() {
585             return asBinder(this);
586         }
587 
588         virtual void         notifyError(int32_t errorCode,
589                                          const CaptureResultExtras& resultExtras);
590 
591         // Check what API level is used for this client. This is used to determine which
592         // superclass this can be cast to.
593         virtual bool canCastToApiClient(apiLevel level) const;
594 
setImageDumpMask(int)595         void setImageDumpMask(int /*mask*/) { }
596     protected:
597         // Initialized in constructor
598 
599         // - The app-side Binder interface to receive callbacks from us
600         sp<hardware::ICameraClient>               mRemoteCallback;
601 
602         int mCameraId;  // All API1 clients use integer camera IDs
603     }; // class Client
604 
605     /**
606      * A listener class that implements the LISTENER interface for use with a ClientManager, and
607      * implements the following methods:
608      *    void onClientRemoved(const ClientDescriptor<KEY, VALUE>& descriptor);
609      *    void onClientAdded(const ClientDescriptor<KEY, VALUE>& descriptor);
610      */
611     class ClientEventListener {
612     public:
613         void onClientAdded(const resource_policy::ClientDescriptor<std::string,
614                 sp<CameraService::BasicClient>>& descriptor);
615         void onClientRemoved(const resource_policy::ClientDescriptor<std::string,
616                 sp<CameraService::BasicClient>>& descriptor);
617     }; // class ClientEventListener
618 
619     typedef std::shared_ptr<resource_policy::ClientDescriptor<std::string,
620             sp<CameraService::BasicClient>>> DescriptorPtr;
621 
622     /**
623      * A container class for managing active camera clients that are using HAL devices.  Active
624      * clients are represented by ClientDescriptor objects that contain strong pointers to the
625      * actual BasicClient subclass binder interface implementation.
626      *
627      * This class manages the eviction behavior for the camera clients.  See the parent class
628      * implementation in utils/ClientManager for the specifics of this behavior.
629      */
630     class CameraClientManager : public resource_policy::ClientManager<std::string,
631             sp<CameraService::BasicClient>, ClientEventListener> {
632     public:
633         CameraClientManager();
634         virtual ~CameraClientManager();
635 
636         /**
637          * Return a strong pointer to the active BasicClient for this camera ID, or an empty
638          * if none exists.
639          */
640         sp<CameraService::BasicClient> getCameraClient(const std::string& id) const;
641 
642         /**
643          * Return a string describing the current state.
644          */
645         std::string toString() const;
646 
647         /**
648          * Make a ClientDescriptor object wrapping the given BasicClient strong pointer.
649          */
650         static DescriptorPtr makeClientDescriptor(const std::string& key,
651                 const sp<BasicClient>& value, int32_t cost,
652                 const std::set<std::string>& conflictingKeys, int32_t score,
653                 int32_t ownerId, int32_t state, int oomScoreOffset, bool systemNativeClient);
654 
655         /**
656          * Make a ClientDescriptor object wrapping the given BasicClient strong pointer with
657          * values intialized from a prior ClientDescriptor.
658          */
659         static DescriptorPtr makeClientDescriptor(const sp<BasicClient>& value,
660                 const CameraService::DescriptorPtr& partial, int oomScoreOffset,
661                 bool systemNativeClient);
662 
663     }; // class CameraClientManager
664 
665     int32_t updateAudioRestriction();
666     int32_t updateAudioRestrictionLocked();
667 
668 private:
669 
670     // TODO: b/263304156 update this to make use of a death callback for more
671     // robust/fault tolerant logging
getActivityManager()672     static const sp<IActivityManager>& getActivityManager() {
673         static const char* kActivityService = "activity";
674         static const auto activityManager = []() -> sp<IActivityManager> {
675             const sp<IServiceManager> sm(defaultServiceManager());
676             if (sm != nullptr) {
677                  return interface_cast<IActivityManager>(sm->checkService(String16(kActivityService)));
678             }
679             return nullptr;
680         }();
681         return activityManager;
682     }
683 
getPermissionController()684     static const sp<IPermissionController>& getPermissionController() {
685         static const char* kPermissionControllerService = "permission";
686         static thread_local sp<IPermissionController> sPermissionController = nullptr;
687 
688         if (sPermissionController == nullptr ||
689                 !IInterface::asBinder(sPermissionController)->isBinderAlive()) {
690             sp<IServiceManager> sm = defaultServiceManager();
691             sp<IBinder> binder = sm->checkService(toString16(kPermissionControllerService));
692             if (binder == nullptr) {
693                 ALOGE("%s: Could not get permission service", __FUNCTION__);
694                 sPermissionController = nullptr;
695             } else {
696                 sPermissionController = interface_cast<IPermissionController>(binder);
697             }
698         }
699 
700         return sPermissionController;
701     }
702 
703     /**
704      * Typesafe version of device status, containing both the HAL-layer and the service interface-
705      * layer values.
706      */
707     enum class StatusInternal : int32_t {
708         NOT_PRESENT = static_cast<int32_t>(CameraDeviceStatus::NOT_PRESENT),
709         PRESENT = static_cast<int32_t>(CameraDeviceStatus::PRESENT),
710         ENUMERATING = static_cast<int32_t>(CameraDeviceStatus::ENUMERATING),
711         NOT_AVAILABLE = static_cast<int32_t>(hardware::ICameraServiceListener::STATUS_NOT_AVAILABLE),
712         UNKNOWN = static_cast<int32_t>(hardware::ICameraServiceListener::STATUS_UNKNOWN)
713     };
714 
715     friend int32_t format_as(StatusInternal s);
716 
717     /**
718      * Container class for the state of each logical camera device, including: ID, status, and
719      * dependencies on other devices.  The mapping of camera ID -> state saved in mCameraStates
720      * represents the camera devices advertised by the HAL (and any USB devices, when we add
721      * those).
722      *
723      * This container does NOT represent an active camera client.  These are represented using
724      * the ClientDescriptors stored in mActiveClientManager.
725      */
726     class CameraState {
727     public:
728 
729         /**
730          * Make a new CameraState and set the ID, cost, and conflicting devices using the values
731          * returned in the HAL's camera_info struct for each device.
732          */
733         CameraState(const std::string& id, int cost, const std::set<std::string>& conflicting,
734                 SystemCameraKind deviceKind, const std::vector<std::string>& physicalCameras);
735         virtual ~CameraState();
736 
737         /**
738          * Return the status for this device.
739          *
740          * This method acquires mStatusLock.
741          */
742         StatusInternal getStatus() const;
743 
744         /**
745          * This function updates the status for this camera device, unless the given status
746          * is in the given list of rejected status states, and execute the function passed in
747          * with a signature onStatusUpdateLocked(const std::string&, int32_t)
748          * if the status has changed.
749          *
750          * This method is idempotent, and will not result in the function passed to
751          * onStatusUpdateLocked being called more than once for the same arguments.
752          * This method aquires mStatusLock.
753          */
754         template<class Func>
755         void updateStatus(StatusInternal status,
756                 const std::string& cameraId,
757                 std::initializer_list<StatusInternal> rejectSourceStates,
758                 Func onStatusUpdatedLocked);
759 
760         /**
761          * Return the last set CameraParameters object generated from the information returned by
762          * the HAL for this device (or an empty CameraParameters object if none has been set).
763          */
764         CameraParameters getShimParams() const;
765 
766         /**
767          * Set the CameraParameters for this device.
768          */
769         void setShimParams(const CameraParameters& params);
770 
771         /**
772          * Return the resource_cost advertised by the HAL for this device.
773          */
774         int getCost() const;
775 
776         /**
777          * Return a set of the IDs of conflicting devices advertised by the HAL for this device.
778          */
779         std::set<std::string> getConflicting() const;
780 
781         /**
782          * Return the kind (SystemCameraKind) of this camera device.
783          */
784         SystemCameraKind getSystemCameraKind() const;
785 
786         /**
787          * Return whether this camera is a logical multi-camera and has a
788          * particular physical sub-camera.
789          */
790         bool containsPhysicalCamera(const std::string& physicalCameraId) const;
791 
792         /**
793          * Add/Remove the unavailable physical camera ID.
794          */
795         bool addUnavailablePhysicalId(const std::string& physicalId);
796         bool removeUnavailablePhysicalId(const std::string& physicalId);
797 
798         /**
799          * Set and get client package name.
800          */
801         void setClientPackage(const std::string& clientPackage);
802         std::string getClientPackage() const;
803 
804         /**
805          * Return the unavailable physical ids for this device.
806          *
807          * This method acquires mStatusLock.
808          */
809         std::vector<std::string> getUnavailablePhysicalIds() const;
810     private:
811         const std::string mId;
812         StatusInternal mStatus; // protected by mStatusLock
813         const int mCost;
814         std::set<std::string> mConflicting;
815         std::set<std::string> mUnavailablePhysicalIds;
816         std::string mClientPackage;
817         mutable Mutex mStatusLock;
818         CameraParameters mShimParams;
819         const SystemCameraKind mSystemCameraKind;
820         const std::vector<std::string> mPhysicalCameras; // Empty if not a logical multi-camera
821     }; // class CameraState
822 
823     // Observer for UID lifecycle enforcing that UIDs in idle
824     // state cannot use the camera to protect user privacy.
825     class UidPolicy :
826         public BnUidObserver,
827         public virtual IBinder::DeathRecipient,
828         public virtual IServiceManager::LocalRegistrationCallback {
829     public:
UidPolicy(sp<CameraService> service)830         explicit UidPolicy(sp<CameraService> service)
831                 : mRegistered(false), mService(service) {}
832 
833         void registerSelf();
834         void unregisterSelf();
835 
836         bool isUidActive(uid_t uid, const std::string &callingPackage);
837         int32_t getProcState(uid_t uid);
838 
839         // IUidObserver
840         void onUidGone(uid_t uid, bool disabled) override;
841         void onUidActive(uid_t uid) override;
842         void onUidIdle(uid_t uid, bool disabled) override;
843         void onUidStateChanged(uid_t uid, int32_t procState, int64_t procStateSeq,
844                 int32_t capability) override;
845         void onUidProcAdjChanged(uid_t uid, int adj) override;
846 
847         void addOverrideUid(uid_t uid, const std::string &callingPackage, bool active);
848         void removeOverrideUid(uid_t uid, const std::string &callingPackage);
849 
850         void registerMonitorUid(uid_t uid, bool openCamera);
851         void unregisterMonitorUid(uid_t uid, bool closeCamera);
852 
853         // Implementation of IServiceManager::LocalRegistrationCallback
854         virtual void onServiceRegistration(const String16& name,
855                         const sp<IBinder>& binder) override;
856         // IBinder::DeathRecipient implementation
857         virtual void binderDied(const wp<IBinder> &who);
858     private:
859         bool isUidActiveLocked(uid_t uid, const std::string &callingPackage);
860         int32_t getProcStateLocked(uid_t uid);
861         void updateOverrideUid(uid_t uid, const std::string &callingPackage, bool active,
862                 bool insert);
863         void registerWithActivityManager();
864 
865         struct MonitoredUid {
866             int32_t procState;
867             int32_t procAdj;
868             bool hasCamera;
869             size_t refCount;
870         };
871 
872         Mutex mUidLock;
873         bool mRegistered;
874         ActivityManager mAm;
875         wp<CameraService> mService;
876         std::unordered_set<uid_t> mActiveUids;
877         // Monitored uid map
878         std::unordered_map<uid_t, MonitoredUid> mMonitoredUids;
879         std::unordered_map<uid_t, bool> mOverrideUids;
880         sp<IBinder> mObserverToken;
881     }; // class UidPolicy
882 
883     // If sensor privacy is enabled then all apps, including those that are active, should be
884     // prevented from accessing the camera.
885     class SensorPrivacyPolicy : public hardware::BnSensorPrivacyListener,
886             public virtual IBinder::DeathRecipient,
887             public virtual IServiceManager::LocalRegistrationCallback,
888             public AttributionAndPermissionUtilsEncapsulator {
889         public:
SensorPrivacyPolicy(wp<CameraService> service,std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils)890             explicit SensorPrivacyPolicy(wp<CameraService> service,
891                     std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils)
892                     : AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils),
893                       mService(service),
894                       mSensorPrivacyEnabled(false),
895                     mCameraPrivacyState(SensorPrivacyManager::DISABLED), mRegistered(false) {}
896 
897             void registerSelf();
898             void unregisterSelf();
899 
900             bool isSensorPrivacyEnabled();
901             bool isCameraPrivacyEnabled();
902             int getCameraPrivacyState();
903             bool isCameraPrivacyEnabled(const String16& packageName);
904 
905             binder::Status onSensorPrivacyChanged(int toggleType, int sensor,
906                                                   bool enabled);
907             binder::Status onSensorPrivacyStateChanged(int toggleType, int sensor, int state);
908 
909             // Implementation of IServiceManager::LocalRegistrationCallback
910             virtual void onServiceRegistration(const String16& name,
911                                                const sp<IBinder>& binder) override;
912             // IBinder::DeathRecipient implementation
913             virtual void binderDied(const wp<IBinder> &who);
914 
915         private:
916             SensorPrivacyManager mSpm;
917             wp<CameraService> mService;
918             Mutex mSensorPrivacyLock;
919             bool mSensorPrivacyEnabled;
920             int mCameraPrivacyState;
921             bool mRegistered;
922 
923             bool hasCameraPrivacyFeature();
924             void registerWithSensorPrivacyManager();
925     };
926 
927     sp<UidPolicy> mUidPolicy;
928 
929     sp<SensorPrivacyPolicy> mSensorPrivacyPolicy;
930 
931     std::shared_ptr<CameraServiceProxyWrapper> mCameraServiceProxyWrapper;
932 
933     // Delay-load the Camera HAL module
934     virtual void onFirstRef();
935 
936     // Eumerate all camera providers in the system
937     status_t enumerateProviders();
938 
939     // Add/remove a new camera to camera and torch state lists or remove an unplugged one
940     // Caller must not hold mServiceLock
941     void addStates(const std::string& id);
942     void removeStates(const std::string& id);
943 
944     // Check if we can connect, before we acquire the service lock.
945     // The returned originalClientPid is the PID of the original process that wants to connect to
946     // camera.
947     // The returned clientPid is the PID of the client that directly connects to camera.
948     // originalClientPid and clientPid are usually the same except when the application uses
949     // mediaserver to connect to camera (using MediaRecorder to connect to camera). In that case,
950     // clientPid is the PID of mediaserver and originalClientPid is the PID of the application.
951     binder::Status validateConnectLocked(const std::string& cameraId, const std::string& clientName,
952             /*inout*/int& clientUid, /*inout*/int& clientPid, /*out*/int& originalClientPid) const;
953     binder::Status validateClientPermissionsLocked(const std::string& cameraId,
954             const std::string& clientName, /*inout*/int& clientUid, /*inout*/int& clientPid,
955             /*out*/int& originalClientPid) const;
956 
957     bool isCameraPrivacyEnabled(const String16& packageName,const std::string& cameraId,
958            int clientPid, int ClientUid);
959 
960     // Handle active client evictions, and update service state.
961     // Only call with with mServiceLock held.
962     status_t handleEvictionsLocked(const std::string& cameraId, int clientPid,
963         apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
964         const std::string& packageName, int scoreOffset, bool systemNativeClient,
965         /*out*/
966         sp<BasicClient>* client,
967         std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial);
968 
969     // Should an operation attempt on a cameraId be rejected ? (this can happen
970     // under various conditions. For example if a camera device is advertised as
971     // system only or hidden secure camera, amongst possible others.
972     bool shouldRejectSystemCameraConnection(const std::string& cameraId) const;
973 
974     // Should a device status update be skipped for a particular camera device ? (this can happen
975     // under various conditions. For example if a camera device is advertised as
976     // system only or hidden secure camera, amongst possible others.
977     bool shouldSkipStatusUpdates(SystemCameraKind systemCameraKind, bool isVendorListener,
978             int clientPid, int clientUid);
979 
980     // Gets the kind of camera device (i.e public, hidden secure or system only)
981     // getSystemCameraKind() needs mInterfaceMutex which might lead to deadlocks
982     // if held along with mStatusListenerLock (depending on lock ordering, b/141756275), it is
983     // recommended that we don't call this function with mStatusListenerLock held.
984     status_t getSystemCameraKind(const std::string& cameraId, SystemCameraKind *kind) const;
985 
986     // Update the set of API1Compatible camera devices without including system
987     // cameras and secure cameras. This is used for hiding system only cameras
988     // from clients using camera1 api and not having android.permission.SYSTEM_CAMERA.
989     // This function expects @param normalDeviceIds, to have normalDeviceIds
990     // sorted in alpha-numeric order.
991     void filterAPI1SystemCameraLocked(const std::vector<std::string> &normalDeviceIds);
992 
993     // In some cases the calling code has no access to the package it runs under.
994     // For example, NDK camera API.
995     // In this case we will get the packages for the calling UID and pick the first one
996     // for attributing the app op. This will work correctly for runtime permissions
997     // as for legacy apps we will toggle the app op for all packages in the UID.
998     // The caveat is that the operation may be attributed to the wrong package and
999     // stats based on app ops may be slightly off.
1000     std::string getPackageNameFromUid(int clientUid);
1001 
1002     // Single implementation shared between the various connect calls
1003     template<class CALLBACK, class CLIENT>
1004     binder::Status connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
1005             int api1CameraId, const std::string& clientPackageNameMaybe, bool systemNativeClient,
1006             const std::optional<std::string>& clientFeatureId, int clientUid, int clientPid,
1007             apiLevel effectiveApiLevel, bool shimUpdateOnly, int scoreOffset, int targetSdkVersion,
1008             int rotationOverride, bool forceSlowJpegMode,
1009             const std::string& originalCameraId,
1010             /*out*/sp<CLIENT>& device);
1011 
1012     // Lock guarding camera service state
1013     Mutex               mServiceLock;
1014 
1015     // Condition to use with mServiceLock, used to handle simultaneous connect calls from clients
1016     std::shared_ptr<WaitableMutexWrapper> mServiceLockWrapper;
1017 
1018     // Return NO_ERROR if the device with a give ID can be connected to
1019     status_t checkIfDeviceIsUsable(const std::string& cameraId) const;
1020 
1021     // Container for managing currently active application-layer clients
1022     CameraClientManager mActiveClientManager;
1023 
1024     // Adds client logs during open session to the file pointed by fd.
1025     void dumpOpenSessionClientLogs(int fd, const Vector<String16>& args,
1026             const std::string& cameraId);
1027 
1028     // Adds client logs during closed session to the file pointed by fd.
1029     void dumpClosedSessionClientLogs(int fd, const std::string& cameraId);
1030 
1031     binder::Status isSessionConfigurationWithParametersSupportedUnsafe(
1032             const std::string& cameraId, const SessionConfiguration& sessionConfiguration,
1033             bool overrideForPerfClass, /*out*/ bool* supported);
1034 
1035     // Mapping from camera ID -> state for each device, map is protected by mCameraStatesLock
1036     std::map<std::string, std::shared_ptr<CameraState>> mCameraStates;
1037 
1038     // Mutex guarding mCameraStates map
1039     mutable Mutex mCameraStatesLock;
1040 
1041     /**
1042      * Resolve the (potentially remapped) camera id for the given input camera id and the given
1043      * device id and device policy (for the device associated with the context of the caller).
1044      *
1045      * For any context associated with a virtual device with custom camera policy, this will return
1046      * the actual camera id if inputCameraId corresponds to the mapped id of a virtual camera
1047      * (for virtual devices with custom camera policy, the back and front virtual cameras of that
1048      * device would have 0 and 1 respectively as their mapped camera id).
1049      */
1050     std::optional<std::string> resolveCameraId(
1051             const std::string& inputCameraId,
1052             int32_t deviceId,
1053             int32_t devicePolicy);
1054 
1055     // Circular buffer for storing event logging for dumps
1056     RingBuffer<std::string> mEventLog;
1057     Mutex mLogLock;
1058 
1059     // set of client package names to watch. if this set contains 'all', then all clients will
1060     // be watched. Access should be guarded by mLogLock
1061     std::set<std::string> mWatchedClientPackages;
1062     // cache of last monitored tags dump immediately before the client disconnects. If a client
1063     // re-connects, its entry is not updated until it disconnects again. Access should be guarded
1064     // by mLogLock
1065     std::map<std::string, std::string> mWatchedClientsDumpCache;
1066 
1067     // The last monitored tags set by client
1068     std::string mMonitorTags;
1069 
1070     // Currently allowed user IDs
1071     std::set<userid_t> mAllowedUsers;
1072 
1073     /**
1074      * Get the camera state for a given camera id.
1075      *
1076      * This acquires mCameraStatesLock.
1077      */
1078     std::shared_ptr<CameraService::CameraState> getCameraState(const std::string& cameraId) const;
1079 
1080     /**
1081      * Evict client who's remote binder has died.  Returns true if this client was in the active
1082      * list and was disconnected.
1083      *
1084      * This method acquires mServiceLock.
1085      */
1086     bool evictClientIdByRemote(const wp<IBinder>& cameraClient);
1087 
1088     /**
1089      * Remove the given client from the active clients list; does not disconnect the client.
1090      *
1091      * This method acquires mServiceLock.
1092      */
1093     void removeByClient(const BasicClient* client);
1094 
1095     /**
1096      * Add new client to active clients list after conflicting clients have disconnected using the
1097      * values set in the partial descriptor passed in to construct the actual client descriptor.
1098      * This is typically called at the end of a connect call.
1099      *
1100      * This method must be called with mServiceLock held.
1101      */
1102     void finishConnectLocked(const sp<BasicClient>& client, const DescriptorPtr& desc,
1103             int oomScoreOffset, bool systemNativeClient);
1104 
1105     /**
1106      * Returns the underlying camera Id string mapped to a camera id int
1107      * Empty string is returned when the cameraIdInt is invalid.
1108      */
1109     std::string cameraIdIntToStr(int cameraIdInt, int32_t deviceId, int32_t devicePolicy);
1110 
1111     /**
1112      * Returns the underlying camera Id string mapped to a camera id int
1113      * Empty string is returned when the cameraIdInt is invalid.
1114      */
1115     std::string cameraIdIntToStrLocked(int cameraIdInt, int32_t deviceId, int32_t devicePolicy);
1116 
1117     /**
1118      * Remove a single client corresponding to the given camera id from the list of active clients.
1119      * If none exists, return an empty strongpointer.
1120      *
1121      * This method must be called with mServiceLock held.
1122      */
1123     sp<CameraService::BasicClient> removeClientLocked(const std::string& cameraId);
1124 
1125     /**
1126      * Handle a notification that the current device user has changed.
1127      */
1128     void doUserSwitch(const std::vector<int32_t>& newUserIds);
1129 
1130     /**
1131      * Add an event log message.
1132      */
1133     void logEvent(const std::string &event);
1134 
1135     /**
1136      * Add an event log message that a client has been disconnected.
1137      */
1138     void logDisconnected(const std::string &cameraId, int clientPid,
1139             const std::string &clientPackage);
1140 
1141     /**
1142      * Add an event log message that a client has been disconnected from offline device.
1143      */
1144     void logDisconnectedOffline(const std::string &cameraId, int clientPid,
1145             const std::string &clientPackage);
1146 
1147     /**
1148      * Add an event log message that an offline client has been connected.
1149      */
1150     void logConnectedOffline(const std::string &cameraId, int clientPid,
1151             const std::string &clientPackage);
1152 
1153     /**
1154      * Add an event log message that a client has been connected.
1155      */
1156     void logConnected(const std::string &cameraId, int clientPid, const std::string &clientPackage);
1157 
1158     /**
1159      * Add an event log message that a client's connect attempt has been rejected.
1160      */
1161     void logRejected(const std::string &cameraId, int clientPid, const std::string &clientPackage,
1162             const std::string &reason);
1163 
1164     /**
1165      * Add an event log message when a client calls setTorchMode succesfully.
1166      */
1167     void logTorchEvent(const std::string &cameraId, const std::string &torchState, int clientPid);
1168 
1169     /**
1170      * Add an event log message that the current device user has been switched.
1171      */
1172     void logUserSwitch(const std::set<userid_t>& oldUserIds,
1173         const std::set<userid_t>& newUserIds);
1174 
1175     /**
1176      * Add an event log message that a device has been removed by the HAL
1177      */
1178     void logDeviceRemoved(const std::string &cameraId, const std::string &reason);
1179 
1180     /**
1181      * Add an event log message that a device has been added by the HAL
1182      */
1183     void logDeviceAdded(const std::string &cameraId, const std::string &reason);
1184 
1185     /**
1186      * Add an event log message that a client has unexpectedly died.
1187      */
1188     void logClientDied(int clientPid, const std::string &reason);
1189 
1190     /**
1191      * Add a event log message that a serious service-level error has occured
1192      * The errorCode should be one of the Android Errors
1193      */
1194     void logServiceError(const std::string &msg, int errorCode);
1195 
1196     /**
1197      * Dump the event log to an FD
1198      */
1199     void dumpEventLog(int fd);
1200 
1201     void cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient *client);
1202 
1203     /**
1204      * This method will acquire mServiceLock
1205      */
1206     void updateCameraNumAndIds();
1207 
1208     /**
1209      * Filter camera characteristics for S Performance class primary cameras.
1210      * mServiceLock should be locked.
1211      */
1212     void filterSPerfClassCharacteristicsLocked();
1213 
1214     // File descriptor to temp file used for caching previous open
1215     // session dumpsys info.
1216     int mMemFd;
1217 
1218     // Number of camera devices (excluding hidden secure cameras)
1219     int                 mNumberOfCameras;
1220     // Number of camera devices (excluding hidden secure cameras and
1221     // system cameras)
1222     int                 mNumberOfCamerasWithoutSystemCamera;
1223 
1224     std::vector<std::string> mNormalDeviceIds;
1225     std::vector<std::string> mNormalDeviceIdsWithoutSystemCamera;
1226     std::set<std::string> mPerfClassPrimaryCameraIds;
1227 
1228     // sounds
1229     sp<MediaPlayer>     newMediaPlayer(const char *file);
1230 
1231     Mutex               mSoundLock;
1232     sp<MediaPlayer>     mSoundPlayer[NUM_SOUNDS];
1233     int                 mSoundRef;  // reference count (release all MediaPlayer when 0)
1234 
1235     // Basic flag on whether the camera subsystem is in a usable state
1236     bool                mInitialized;
1237 
1238     sp<CameraProviderManager> mCameraProviderManager;
1239 
1240     class ServiceListener : public virtual IBinder::DeathRecipient {
1241         public:
ServiceListener(sp<CameraService> parent,sp<hardware::ICameraServiceListener> listener,int uid,int pid,bool isVendorClient,bool openCloseCallbackAllowed)1242             ServiceListener(sp<CameraService> parent, sp<hardware::ICameraServiceListener> listener,
1243                     int uid, int pid, bool isVendorClient, bool openCloseCallbackAllowed)
1244                     : mParent(parent), mListener(listener), mListenerUid(uid), mListenerPid(pid),
1245                       mIsVendorListener(isVendorClient),
1246                       mOpenCloseCallbackAllowed(openCloseCallbackAllowed) { }
1247 
initialize(bool isProcessLocalTest)1248             status_t initialize(bool isProcessLocalTest) {
1249                 if (isProcessLocalTest) {
1250                     return OK;
1251                 }
1252                 return IInterface::asBinder(mListener)->linkToDeath(this);
1253             }
1254 
1255             template<typename... args_t>
handleBinderStatus(const binder::Status & ret,const char * logOnError,args_t...args)1256             void handleBinderStatus(const binder::Status &ret, const char *logOnError,
1257                     args_t... args) {
1258                 if (!ret.isOk() &&
1259                         (ret.exceptionCode() != binder::Status::Exception::EX_TRANSACTION_FAILED
1260                         || !mLastTransactFailed)) {
1261                     ALOGE(logOnError, args...);
1262                 }
1263 
1264                 // If the transaction failed, the process may have died (or other things, see
1265                 // b/28321379). Mute consecutive errors from this listener to avoid log spam.
1266                 if (ret.exceptionCode() == binder::Status::Exception::EX_TRANSACTION_FAILED) {
1267                     if (!mLastTransactFailed) {
1268                         ALOGE("%s: Muting similar errors from listener %d:%d", __FUNCTION__,
1269                                 mListenerUid, mListenerPid);
1270                     }
1271                     mLastTransactFailed = true;
1272                 } else {
1273                     // Reset mLastTransactFailed when binder becomes healthy again.
1274                     mLastTransactFailed = false;
1275                 }
1276             }
1277 
binderDied(const wp<IBinder> &)1278             virtual void binderDied(const wp<IBinder> &/*who*/) {
1279                 auto parent = mParent.promote();
1280                 if (parent.get() != nullptr) {
1281                     parent->removeListener(mListener);
1282                 }
1283             }
1284 
getListenerUid()1285             int getListenerUid() { return mListenerUid; }
getListenerPid()1286             int getListenerPid() { return mListenerPid; }
getListener()1287             sp<hardware::ICameraServiceListener> getListener() { return mListener; }
isVendorListener()1288             bool isVendorListener() { return mIsVendorListener; }
isOpenCloseCallbackAllowed()1289             bool isOpenCloseCallbackAllowed() { return mOpenCloseCallbackAllowed; }
1290 
1291         private:
1292             wp<CameraService> mParent;
1293             sp<hardware::ICameraServiceListener> mListener;
1294             int mListenerUid = -1;
1295             int mListenerPid = -1;
1296             bool mIsVendorListener = false;
1297             bool mOpenCloseCallbackAllowed = false;
1298 
1299             // Flag for preventing log spam when binder becomes unhealthy
1300             bool mLastTransactFailed = false;
1301     };
1302 
1303     // Guarded by mStatusListenerMutex
1304     std::vector<sp<ServiceListener>> mListenerList;
1305 
1306     Mutex       mStatusListenerLock;
1307 
1308     /**
1309      * Update the status for the given camera id (if that device exists), and broadcast the
1310      * status update to all current ICameraServiceListeners if the status has changed.  Any
1311      * statuses in rejectedSourceStates will be ignored.
1312      *
1313      * This method must be idempotent.
1314      * This method acquires mStatusLock and mStatusListenerLock.
1315      * For any virtual camera, this method must pass its mapped camera id and device id to
1316      * ICameraServiceListeners (using mVirtualDeviceCameraIdMapper).
1317      */
1318     void updateStatus(StatusInternal status,
1319             const std::string& cameraId,
1320             std::initializer_list<StatusInternal>
1321                 rejectedSourceStates);
1322     void updateStatus(StatusInternal status,
1323             const std::string& cameraId);
1324 
1325     /**
1326      * Update the opened/closed status of the given camera id.
1327      *
1328      * This method acqiures mStatusListenerLock.
1329      */
1330     void updateOpenCloseStatus(const std::string& cameraId, bool open,
1331             const std::string& packageName);
1332 
1333     // flashlight control
1334     sp<CameraFlashlight> mFlashlight;
1335     // guard mTorchStatusMap
1336     Mutex                mTorchStatusMutex;
1337     // guard mTorchClientMap
1338     Mutex                mTorchClientMapMutex;
1339     // guard mTorchUidMap
1340     Mutex                mTorchUidMapMutex;
1341     // camera id -> torch status
1342     KeyedVector<std::string, TorchModeStatus>
1343             mTorchStatusMap;
1344     // camera id -> torch client binder
1345     // only store the last client that turns on each camera's torch mode
1346     KeyedVector<std::string, sp<IBinder>> mTorchClientMap;
1347     // camera id -> [incoming uid, current uid] pair
1348     std::map<std::string, std::pair<int, int>> mTorchUidMap;
1349 
1350     // check and handle if torch client's process has died
1351     void handleTorchClientBinderDied(const wp<IBinder> &who);
1352 
1353     // handle torch mode status change and invoke callbacks. mTorchStatusMutex
1354     // should be locked.
1355     void onTorchStatusChangedLocked(const std::string& cameraId,
1356             TorchModeStatus newStatus,
1357             SystemCameraKind systemCameraKind);
1358 
1359     // get a camera's torch status. mTorchStatusMutex should be locked.
1360     status_t getTorchStatusLocked(const std::string &cameraId,
1361              TorchModeStatus *status) const;
1362 
1363     // set a camera's torch status. mTorchStatusMutex should be locked.
1364     status_t setTorchStatusLocked(const std::string &cameraId,
1365             TorchModeStatus status);
1366 
1367     // notify physical camera status when the physical camera is public.
1368     // Expects mStatusListenerLock to be locked.
1369     void notifyPhysicalCameraStatusLocked(int32_t status, const std::string& physicalCameraId,
1370             const std::list<std::string>& logicalCameraIds, SystemCameraKind deviceKind,
1371             int32_t virtualDeviceId);
1372 
1373     // get list of logical cameras which are backed by physicalCameraId
1374     std::list<std::string> getLogicalCameras(const std::string& physicalCameraId);
1375 
1376 
1377     // IBinder::DeathRecipient implementation
1378     virtual void        binderDied(const wp<IBinder> &who);
1379 
1380     /**
1381      * Initialize and cache the metadata used by the HAL1 shim for a given cameraId.
1382      *
1383      * Sets Status to a service-specific error on failure
1384      */
1385     binder::Status      initializeShimMetadata(int cameraId);
1386 
1387     /**
1388      * Get the cached CameraParameters for the camera. If they haven't been
1389      * cached yet, then initialize them for the first time.
1390      *
1391      * Sets Status to a service-specific error on failure
1392      */
1393     binder::Status      getLegacyParametersLazy(int cameraId, /*out*/CameraParameters* parameters);
1394 
1395     // Blocks all clients from the UID
1396     void blockClientsForUid(uid_t uid);
1397 
1398     // Blocks all active clients.
1399     void blockAllClients();
1400 
1401     // Blocks clients whose privacy is enabled.
1402     void blockPrivacyEnabledClients();
1403 
1404     // Overrides the UID state as if it is idle
1405     status_t handleSetUidState(const Vector<String16>& args, int err);
1406 
1407     // Clears the override for the UID state
1408     status_t handleResetUidState(const Vector<String16>& args, int err);
1409 
1410     // Gets the UID state
1411     status_t handleGetUidState(const Vector<String16>& args, int out, int err);
1412 
1413     // Set the rotate-and-crop AUTO override behavior
1414     status_t handleSetRotateAndCrop(const Vector<String16>& args);
1415 
1416     // Get the rotate-and-crop AUTO override behavior
1417     status_t handleGetRotateAndCrop(int out);
1418 
1419     // Set the autoframing AUTO override behaviour.
1420     status_t handleSetAutoframing(const Vector<String16>& args);
1421 
1422     // Get the autoframing AUTO override behaviour
1423     status_t handleGetAutoframing(int out);
1424 
1425     // Set the mask for image dump to disk
1426     status_t handleSetImageDumpMask(const Vector<String16>& args);
1427 
1428     // Get the mask for image dump to disk
1429     status_t handleGetImageDumpMask(int out);
1430 
1431     // Set the camera mute state
1432     status_t handleSetCameraMute(const Vector<String16>& args);
1433 
1434     // Set the stream use case overrides
1435     status_t handleSetStreamUseCaseOverrides(const Vector<String16>& args);
1436 
1437     // Clear the stream use case overrides
1438     void handleClearStreamUseCaseOverrides();
1439 
1440     // Set or clear the zoom override flag
1441     status_t handleSetZoomOverride(const Vector<String16>& args);
1442 
1443     // Set Camera Id remapping using 'cmd'
1444     status_t handleCameraIdRemapping(const Vector<String16>& args, int errFd);
1445 
1446     // Handle 'watch' command as passed through 'cmd'
1447     status_t handleWatchCommand(const Vector<String16> &args, int inFd, int outFd);
1448 
1449     // Set the camera service watchdog
1450     status_t handleSetCameraServiceWatchdog(const Vector<String16>& args);
1451 
1452     // Enable tag monitoring of the given tags in provided clients
1453     status_t startWatchingTags(const Vector<String16> &args, int outFd);
1454 
1455     // Disable tag monitoring
1456     status_t stopWatchingTags(int outFd);
1457 
1458     // Clears mWatchedClientsDumpCache
1459     status_t clearCachedMonitoredTagDumps(int outFd);
1460 
1461     // Print events of monitored tags in all cached and attached clients
1462     status_t printWatchedTags(int outFd);
1463 
1464     // Print events of monitored tags in all attached clients as they are captured. New events are
1465     // fetched every `refreshMillis` ms
1466     // NOTE: This function does not terminate until user passes '\n' to inFd.
1467     status_t printWatchedTagsUntilInterrupt(const Vector<String16> &args, int inFd, int outFd);
1468 
1469     // Parses comma separated clients list and adds them to mWatchedClientPackages.
1470     // Does not acquire mLogLock before modifying mWatchedClientPackages. It is the caller's
1471     // responsibility to acquire mLogLock before calling this function.
1472     void parseClientsToWatchLocked(const std::string &clients);
1473 
1474     // Prints the shell command help
1475     status_t printHelp(int out);
1476 
1477     // Returns true if client should monitor tags based on the contents of mWatchedClientPackages.
1478     // Acquires mLogLock before querying mWatchedClientPackages.
1479     bool isClientWatched(const BasicClient *client);
1480 
1481     // Returns true if client should monitor tags based on the contents of mWatchedClientPackages.
1482     // Does not acquire mLogLock before querying mWatchedClientPackages. It is the caller's
1483     // responsibility to acquire mLogLock before calling this functions.
1484     bool isClientWatchedLocked(const BasicClient *client);
1485 
1486     // Filters out fingerprintable keys if the calling process does not have CAMERA permission.
1487     // Note: function caller should ensure that shouldRejectSystemCameraConnection is checked
1488     // for the calling process before calling this function.
1489     binder::Status filterSensitiveMetadataIfNeeded(const std::string& cameraId,
1490                                                    CameraMetadata* metadata);
1491 
1492     /**
1493      * Get the current system time as a formatted string.
1494      */
1495     static std::string getFormattedCurrentTime();
1496 
1497     static binder::Status makeClient(const sp<CameraService>& cameraService,
1498             const sp<IInterface>& cameraCb, const std::string& packageName,
1499             bool systemNativeClient, const std::optional<std::string>& featureId,
1500             const std::string& cameraId, int api1CameraId, int facing, int sensorOrientation,
1501             int clientPid, uid_t clientUid, int servicePid,
1502             std::pair<int, IPCTransport> deviceVersionAndIPCTransport, apiLevel effectiveApiLevel,
1503             bool overrideForPerfClass, int rotationOverride, bool forceSlowJpegMode,
1504             const std::string& originalCameraId,
1505             /*out*/ sp<BasicClient>* client);
1506 
1507     static std::string toString(std::set<userid_t> intSet);
1508     static int32_t mapToInterface(TorchModeStatus status);
1509     static StatusInternal mapToInternal(CameraDeviceStatus status);
1510     static int32_t mapToInterface(StatusInternal status);
1511 
1512 
1513     void broadcastTorchModeStatus(const std::string& cameraId,
1514             TorchModeStatus status, SystemCameraKind systemCameraKind);
1515 
1516     void broadcastTorchStrengthLevel(const std::string& cameraId, int32_t newTorchStrengthLevel);
1517 
1518     void disconnectClient(const std::string& id, sp<BasicClient> clientToDisconnect);
1519 
1520     // Regular online and offline devices must not be in conflict at camera service layer.
1521     // Use separate keys for offline devices.
1522     static const std::string kOfflineDevice;
1523 
1524     // Sentinel value to be stored in `mWatchedClientsPackages` to indicate that all clients should
1525     // be watched.
1526     static const std::string kWatchAllClientsFlag;
1527 
1528     // TODO: right now each BasicClient holds one AppOpsManager instance.
1529     // We can refactor the code so all of clients share this instance
1530     AppOpsManager mAppOps;
1531 
1532     // Aggreated audio restriction mode for all camera clients
1533     int32_t mAudioRestriction;
1534 
1535     // Current override cmd rotate-and-crop mode; AUTO means no override
1536     uint8_t mOverrideRotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
1537 
1538     // Current autoframing mode
1539     uint8_t mOverrideAutoframingMode = ANDROID_CONTROL_AUTOFRAMING_AUTO;
1540 
1541     // Current image dump mask
1542     uint8_t mImageDumpMask = 0;
1543 
1544     // Current camera mute mode
1545     bool mOverrideCameraMuteMode = false;
1546 
1547     // Camera Service watchdog flag
1548     bool mCameraServiceWatchdogEnabled = true;
1549 
1550     // Current stream use case overrides
1551     std::vector<int64_t> mStreamUseCaseOverrides;
1552 
1553     // Current zoom override value
1554     int32_t mZoomOverrideValue = -1;
1555 
1556     /**
1557      * A listener class that implements the IBinder::DeathRecipient interface
1558      * for use to call back the error state injected by the external camera, and
1559      * camera service can kill the injection when binder signals process death.
1560      */
1561     class InjectionStatusListener : public virtual IBinder::DeathRecipient {
1562         public:
InjectionStatusListener(sp<CameraService> parent)1563             InjectionStatusListener(sp<CameraService> parent) : mParent(parent) {}
1564 
1565             void addListener(const sp<hardware::camera2::ICameraInjectionCallback>& callback);
1566             void removeListener();
1567             void notifyInjectionError(const std::string &injectedCamId, status_t err);
1568 
1569             // IBinder::DeathRecipient implementation
1570             virtual void binderDied(const wp<IBinder>& who);
1571 
1572         private:
1573             Mutex mListenerLock;
1574             wp<CameraService> mParent;
1575             sp<hardware::camera2::ICameraInjectionCallback> mCameraInjectionCallback;
1576     };
1577 
1578     sp<InjectionStatusListener> mInjectionStatusListener;
1579 
1580     /**
1581      * A class that implements the hardware::camera2::BnCameraInjectionSession interface
1582      */
1583     class CameraInjectionSession : public hardware::camera2::BnCameraInjectionSession {
1584         public:
CameraInjectionSession(sp<CameraService> parent)1585             CameraInjectionSession(sp<CameraService> parent) : mParent(parent) {}
~CameraInjectionSession()1586             virtual ~CameraInjectionSession() {}
1587             binder::Status stopInjection() override;
1588 
1589         private:
1590             Mutex mInjectionSessionLock;
1591             wp<CameraService> mParent;
1592     };
1593 
1594     // When injecting the camera, it will check whether the injecting camera status is unavailable.
1595     // If it is, the disconnect function will be called to to prevent camera access on the device.
1596     status_t checkIfInjectionCameraIsPresent(const std::string& externalCamId,
1597             sp<BasicClient> clientSp);
1598 
1599     void clearInjectionParameters();
1600 
1601     // This is the existing camera id being replaced.
1602     std::string mInjectionInternalCamId;
1603     // This is the external camera Id replacing the internalId.
1604     std::string mInjectionExternalCamId;
1605     bool mInjectionInitPending = false;
1606     // Guard mInjectionInternalCamId and mInjectionInitPending.
1607     Mutex mInjectionParametersLock;
1608 
1609     // Track the folded/unfoled device state. 0 == UNFOLDED, 4 == FOLDED
1610     int64_t mDeviceState;
1611 
1612     void updateTorchUidMapLocked(const std::string& cameraId, int uid);
1613 
1614     VirtualDeviceCameraIdMapper mVirtualDeviceCameraIdMapper;
1615 };
1616 
1617 } // namespace android
1618 
1619 #endif
1620