• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2005 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 #pragma once
18 #include <binder/Common.h>
19 #include <binder/IInterface.h>
20 // Trusty has its own definition of socket APIs from trusty_ipc.h
21 #ifndef __TRUSTY__
22 #include <sys/socket.h>
23 #endif // __TRUSTY__
24 #include <utils/String16.h>
25 #include <utils/Vector.h>
26 #include <optional>
27 #include <set>
28 
29 namespace android {
30 
31 /**
32  * Service manager for C++ services.
33  *
34  * IInterface is only for legacy ABI compatibility
35  */
36 class LIBBINDER_EXPORTED IServiceManager : public IInterface {
37 public:
38     // for ABI compatibility
39     virtual const String16& getInterfaceDescriptor() const;
40 
41     IServiceManager();
42     virtual ~IServiceManager();
43 
44     /**
45      * Must match values in IServiceManager.aidl
46      */
47     /* Allows services to dump sections according to priorities. */
48     static const int DUMP_FLAG_PRIORITY_CRITICAL = 1 << 0;
49     static const int DUMP_FLAG_PRIORITY_HIGH = 1 << 1;
50     static const int DUMP_FLAG_PRIORITY_NORMAL = 1 << 2;
51     /**
52      * Services are by default registered with a DEFAULT dump priority. DEFAULT priority has the
53      * same priority as NORMAL priority but the services are not called with dump priority
54      * arguments.
55      */
56     static const int DUMP_FLAG_PRIORITY_DEFAULT = 1 << 3;
57     static const int DUMP_FLAG_PRIORITY_ALL = DUMP_FLAG_PRIORITY_CRITICAL |
58             DUMP_FLAG_PRIORITY_HIGH | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PRIORITY_DEFAULT;
59     static const int DUMP_FLAG_PROTO = 1 << 4;
60 
61     /**
62      * Retrieve an existing service, blocking for a few seconds if it doesn't yet exist. This
63      * does polling. A more efficient way to make sure you unblock as soon as the service is
64      * available is to use waitForService or to use service notifications.
65      *
66      * Warning: when using this API, typically, you should call it in a loop. It's dangerous to
67      * assume that nullptr could mean that the service is not available. The service could just
68      * be starting. Generally, whether a service exists, this information should be declared
69      * externally (for instance, an Android feature might imply the existence of a service,
70      * a system property, or in the case of services in the VINTF manifest, it can be checked
71      * with isDeclared).
72      */
73     [[deprecated("this polls for 5s, prefer waitForService or checkService")]]
74     virtual sp<IBinder> getService(const String16& name) const = 0;
75 
76     /**
77      * Retrieve an existing service, non-blocking.
78      */
79     virtual sp<IBinder>         checkService( const String16& name) const = 0;
80 
81     /**
82      * Register a service.
83      *
84      * Note:
85      * This status_t return value may be an exception code from an underlying
86      * Status type that doesn't have a representive error code in
87      * utils/Errors.h.
88      * One example of this is a return value of -7
89      * (Status::Exception::EX_UNSUPPORTED_OPERATION) when the service manager
90      * process is not installed on the device when addService is called.
91      */
92     // NOLINTNEXTLINE(google-default-arguments)
93     virtual status_t addService(const String16& name, const sp<IBinder>& service,
94                                 bool allowIsolated = false,
95                                 int dumpsysFlags = DUMP_FLAG_PRIORITY_DEFAULT) = 0;
96 
97     /**
98      * Return list of all existing services.
99      */
100     // NOLINTNEXTLINE(google-default-arguments)
101     virtual Vector<String16> listServices(int dumpsysFlags = DUMP_FLAG_PRIORITY_ALL) = 0;
102 
103     /**
104      * Efficiently wait for a service.
105      *
106      * Returns nullptr only for permission problem or fatal error.
107      */
108     virtual sp<IBinder> waitForService(const String16& name) = 0;
109 
110     /**
111      * Check if a service is declared (e.g. VINTF manifest).
112      *
113      * If this returns true, waitForService should always be able to return the
114      * service.
115      */
116     virtual bool isDeclared(const String16& name) = 0;
117 
118     /**
119      * Get all instances of a service as declared in the VINTF manifest
120      */
121     virtual Vector<String16> getDeclaredInstances(const String16& interface) = 0;
122 
123     /**
124      * If this instance is updatable via an APEX, returns the APEX with which
125      * this can be updated.
126      */
127     virtual std::optional<String16> updatableViaApex(const String16& name) = 0;
128 
129     /**
130      * Returns all instances which are updatable via the APEX. Instance names are fully qualified
131      * like `pack.age.IFoo/default`.
132      */
133     virtual Vector<String16> getUpdatableNames(const String16& apexName) = 0;
134 
135     /**
136      * If this instance has declared remote connection information, returns
137      * the ConnectionInfo.
138      */
139     struct ConnectionInfo {
140         std::string ipAddress;
141         unsigned int port;
142     };
143     virtual std::optional<ConnectionInfo> getConnectionInfo(const String16& name) = 0;
144 
145     struct LocalRegistrationCallback : public virtual RefBase {
146         virtual void onServiceRegistration(const String16& instance, const sp<IBinder>& binder) = 0;
~LocalRegistrationCallbackLocalRegistrationCallback147         virtual ~LocalRegistrationCallback() {}
148     };
149 
150     virtual status_t registerForNotifications(const String16& name,
151                                               const sp<LocalRegistrationCallback>& callback) = 0;
152 
153     virtual status_t unregisterForNotifications(const String16& name,
154                                                 const sp<LocalRegistrationCallback>& callback) = 0;
155 
156     struct ServiceDebugInfo {
157         std::string name;
158         int pid;
159     };
160     virtual std::vector<ServiceDebugInfo> getServiceDebugInfo() = 0;
161 
162     /**
163      * Directly enable or disable caching binder during addService calls.
164      * Only used for testing. This is enabled by default.
165      */
166     virtual void enableAddServiceCache(bool value) = 0;
167 };
168 
169 LIBBINDER_EXPORTED sp<IServiceManager> defaultServiceManager();
170 
171 /**
172  * Directly set the default service manager. Only used for testing.
173  * Note that the caller is responsible for caling this method
174  * *before* any call to defaultServiceManager(); if the latter is
175  * called first, setDefaultServiceManager() will abort.
176  */
177 LIBBINDER_EXPORTED void setDefaultServiceManager(const sp<IServiceManager>& sm);
178 
179 template<typename INTERFACE>
waitForService(const String16 & name)180 sp<INTERFACE> waitForService(const String16& name) {
181     const sp<IServiceManager> sm = defaultServiceManager();
182     return interface_cast<INTERFACE>(sm->waitForService(name));
183 }
184 
185 template<typename INTERFACE>
waitForDeclaredService(const String16 & name)186 sp<INTERFACE> waitForDeclaredService(const String16& name) {
187     const sp<IServiceManager> sm = defaultServiceManager();
188     if (!sm->isDeclared(name)) return nullptr;
189     return interface_cast<INTERFACE>(sm->waitForService(name));
190 }
191 
192 template <typename INTERFACE>
checkDeclaredService(const String16 & name)193 sp<INTERFACE> checkDeclaredService(const String16& name) {
194     const sp<IServiceManager> sm = defaultServiceManager();
195     if (!sm->isDeclared(name)) return nullptr;
196     return interface_cast<INTERFACE>(sm->checkService(name));
197 }
198 
199 template<typename INTERFACE>
200 sp<INTERFACE> waitForVintfService(
201         const String16& instance = String16("default")) {
202     return waitForDeclaredService<INTERFACE>(
203         INTERFACE::descriptor + String16("/") + instance);
204 }
205 
206 template<typename INTERFACE>
207 sp<INTERFACE> checkVintfService(
208         const String16& instance = String16("default")) {
209     return checkDeclaredService<INTERFACE>(
210         INTERFACE::descriptor + String16("/") + instance);
211 }
212 
213 template<typename INTERFACE>
getService(const String16 & name,sp<INTERFACE> * outService)214 status_t getService(const String16& name, sp<INTERFACE>* outService)
215 {
216     const sp<IServiceManager> sm = defaultServiceManager();
217     if (sm != nullptr) {
218 #pragma clang diagnostic push
219 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
220         *outService = interface_cast<INTERFACE>(sm->getService(name));
221 #pragma clang diagnostic pop // getService deprecation
222         if ((*outService) != nullptr) return NO_ERROR;
223     }
224     return NAME_NOT_FOUND;
225 }
226 
227 LIBBINDER_EXPORTED void* openDeclaredPassthroughHal(const String16& interface,
228                                                     const String16& instance, int flag);
229 
230 LIBBINDER_EXPORTED bool checkCallingPermission(const String16& permission);
231 LIBBINDER_EXPORTED bool checkCallingPermission(const String16& permission, int32_t* outPid,
232                                                int32_t* outUid);
233 LIBBINDER_EXPORTED bool checkPermission(const String16& permission, pid_t pid, uid_t uid,
234                                         bool logPermissionFailure = true);
235 
236 // ----------------------------------------------------------------------
237 // Trusty's definition of the socket APIs does not include sockaddr types
238 #ifndef __TRUSTY__
239 typedef std::function<status_t(const String16& name, sockaddr* outAddr, socklen_t addrSize)>
240         RpcSocketAddressProvider;
241 
242 /**
243  * This callback provides a way for clients to get access to remote services by
244  * providing an Accessor object from libbinder that can connect to the remote
245  * service over sockets.
246  *
247  * \param instance name of the service that the callback will provide an
248  *        Accessor for. The provided accessor will be used to set up a client
249  *        RPC connection in libbinder in order to return a binder for the
250  *        associated remote service.
251  *
252  * \return IBinder of the Accessor object that libbinder implements.
253  *         nullptr if the provider callback doesn't know how to reach the
254  *         service or doesn't want to provide access for any other reason.
255  */
256 typedef std::function<sp<IBinder>(const String16& instance)> RpcAccessorProvider;
257 
258 class AccessorProvider;
259 
260 /**
261  * Register a RpcAccessorProvider for the service manager APIs.
262  *
263  * \param instances that the RpcAccessorProvider knows about and can provide an
264  *        Accessor for.
265  * \param provider callback that generates Accessors.
266  *
267  * \return A pointer used as a recept for the successful addition of the
268  *         AccessorProvider. This is needed to unregister it later.
269  */
270 [[nodiscard]] LIBBINDER_EXPORTED std::weak_ptr<AccessorProvider> addAccessorProvider(
271         std::set<std::string>&& instances, RpcAccessorProvider&& providerCallback);
272 
273 /**
274  * Remove an accessor provider using the pointer provided by addAccessorProvider
275  * along with the cookie pointer that was used.
276  *
277  * \param provider cookie that was returned by addAccessorProvider to keep track
278  *        of this instance.
279  */
280 [[nodiscard]] LIBBINDER_EXPORTED status_t
281 removeAccessorProvider(std::weak_ptr<AccessorProvider> provider);
282 
283 /**
284  * Create an Accessor associated with a service that can create a socket connection based
285  * on the connection info from the supplied RpcSocketAddressProvider.
286  *
287  * \param instance name of the service that this Accessor is associated with
288  * \param connectionInfoProvider a callback that returns connection info for
289  *        connecting to the service.
290  * \return the binder of the IAccessor implementation from libbinder
291  */
292 LIBBINDER_EXPORTED sp<IBinder> createAccessor(const String16& instance,
293                                               RpcSocketAddressProvider&& connectionInfoProvider);
294 
295 /**
296  * Check to make sure this binder is the expected binder that is an IAccessor
297  * associated with a specific instance.
298  *
299  * This helper function exists to avoid adding the IAccessor type to
300  * libbinder_ndk.
301  *
302  * \param instance name of the service that this Accessor should be associated with
303  * \param binder to validate
304  *
305  * \return OK if the binder is an IAccessor for `instance`
306  */
307 LIBBINDER_EXPORTED status_t validateAccessor(const String16& instance, const sp<IBinder>& binder);
308 
309 /**
310  * Have libbinder wrap this IAccessor binder in an IAccessorDelegator and return
311  * it.
312  *
313  * This is required only in very specific situations when the process that has
314  * permissions to connect the to RPC service's socket and create the FD for it
315  * is in a separate process from this process that wants to service the Accessor
316  * binder and the communication between these two processes is binder RPC. This
317  * is needed because the binder passed over the binder RPC connection can not be
318  * used as a kernel binder, and needs to be wrapped by a kernel binder that can
319  * then be registered with service manager.
320  *
321  * \param instance name of the Accessor.
322  * \param binder to wrap in a Delegator and register with service manager.
323  * \param outDelegator the wrapped kernel binder for IAccessorDelegator
324  *
325  * \return OK if the binder is an IAccessor for `instance` and the delegator was
326  * successfully created.
327  */
328 LIBBINDER_EXPORTED status_t delegateAccessor(const String16& name, const sp<IBinder>& accessor,
329                                              sp<IBinder>* delegator);
330 #endif // __TRUSTY__
331 
332 #ifndef __ANDROID__
333 // Create an IServiceManager that delegates the service manager on the device via adb.
334 // This is can be set as the default service manager at program start, so that
335 // defaultServiceManager() returns it:
336 //    int main() {
337 //        setDefaultServiceManager(createRpcDelegateServiceManager());
338 //        auto sm = defaultServiceManager();
339 //        // ...
340 //    }
341 // Resources are cleaned up when the object is destroyed.
342 //
343 // For each returned binder object, at most |maxOutgoingConnections| outgoing connections are
344 // instantiated, depending on how many the service on the device is configured with.
345 // Hence, only |maxOutgoingConnections| calls can be made simultaneously.
346 // See also RpcSession::setMaxOutgoingConnections.
347 struct RpcDelegateServiceManagerOptions {
348     std::optional<size_t> maxOutgoingConnections;
349 };
350 LIBBINDER_EXPORTED sp<IServiceManager> createRpcDelegateServiceManager(
351         const RpcDelegateServiceManagerOptions& options);
352 #endif
353 
354 } // namespace android
355