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     // NOLINTNEXTLINE(google-default-arguments)
85     virtual status_t addService(const String16& name, const sp<IBinder>& service,
86                                 bool allowIsolated = false,
87                                 int dumpsysFlags = DUMP_FLAG_PRIORITY_DEFAULT) = 0;
88 
89     /**
90      * Return list of all existing services.
91      */
92     // NOLINTNEXTLINE(google-default-arguments)
93     virtual Vector<String16> listServices(int dumpsysFlags = DUMP_FLAG_PRIORITY_ALL) = 0;
94 
95     /**
96      * Efficiently wait for a service.
97      *
98      * Returns nullptr only for permission problem or fatal error.
99      */
100     virtual sp<IBinder> waitForService(const String16& name) = 0;
101 
102     /**
103      * Check if a service is declared (e.g. VINTF manifest).
104      *
105      * If this returns true, waitForService should always be able to return the
106      * service.
107      */
108     virtual bool isDeclared(const String16& name) = 0;
109 
110     /**
111      * Get all instances of a service as declared in the VINTF manifest
112      */
113     virtual Vector<String16> getDeclaredInstances(const String16& interface) = 0;
114 
115     /**
116      * If this instance is updatable via an APEX, returns the APEX with which
117      * this can be updated.
118      */
119     virtual std::optional<String16> updatableViaApex(const String16& name) = 0;
120 
121     /**
122      * Returns all instances which are updatable via the APEX. Instance names are fully qualified
123      * like `pack.age.IFoo/default`.
124      */
125     virtual Vector<String16> getUpdatableNames(const String16& apexName) = 0;
126 
127     /**
128      * If this instance has declared remote connection information, returns
129      * the ConnectionInfo.
130      */
131     struct ConnectionInfo {
132         std::string ipAddress;
133         unsigned int port;
134     };
135     virtual std::optional<ConnectionInfo> getConnectionInfo(const String16& name) = 0;
136 
137     struct LocalRegistrationCallback : public virtual RefBase {
138         virtual void onServiceRegistration(const String16& instance, const sp<IBinder>& binder) = 0;
~LocalRegistrationCallbackLocalRegistrationCallback139         virtual ~LocalRegistrationCallback() {}
140     };
141 
142     virtual status_t registerForNotifications(const String16& name,
143                                               const sp<LocalRegistrationCallback>& callback) = 0;
144 
145     virtual status_t unregisterForNotifications(const String16& name,
146                                                 const sp<LocalRegistrationCallback>& callback) = 0;
147 
148     struct ServiceDebugInfo {
149         std::string name;
150         int pid;
151     };
152     virtual std::vector<ServiceDebugInfo> getServiceDebugInfo() = 0;
153 
154     /**
155      * Directly enable or disable caching binder during addService calls.
156      * Only used for testing. This is enabled by default.
157      */
158     virtual void enableAddServiceCache(bool value) = 0;
159 };
160 
161 LIBBINDER_EXPORTED sp<IServiceManager> defaultServiceManager();
162 
163 /**
164  * Directly set the default service manager. Only used for testing.
165  * Note that the caller is responsible for caling this method
166  * *before* any call to defaultServiceManager(); if the latter is
167  * called first, setDefaultServiceManager() will abort.
168  */
169 LIBBINDER_EXPORTED void setDefaultServiceManager(const sp<IServiceManager>& sm);
170 
171 template<typename INTERFACE>
waitForService(const String16 & name)172 sp<INTERFACE> waitForService(const String16& name) {
173     const sp<IServiceManager> sm = defaultServiceManager();
174     return interface_cast<INTERFACE>(sm->waitForService(name));
175 }
176 
177 template<typename INTERFACE>
waitForDeclaredService(const String16 & name)178 sp<INTERFACE> waitForDeclaredService(const String16& name) {
179     const sp<IServiceManager> sm = defaultServiceManager();
180     if (!sm->isDeclared(name)) return nullptr;
181     return interface_cast<INTERFACE>(sm->waitForService(name));
182 }
183 
184 template <typename INTERFACE>
checkDeclaredService(const String16 & name)185 sp<INTERFACE> checkDeclaredService(const String16& name) {
186     const sp<IServiceManager> sm = defaultServiceManager();
187     if (!sm->isDeclared(name)) return nullptr;
188     return interface_cast<INTERFACE>(sm->checkService(name));
189 }
190 
191 template<typename INTERFACE>
192 sp<INTERFACE> waitForVintfService(
193         const String16& instance = String16("default")) {
194     return waitForDeclaredService<INTERFACE>(
195         INTERFACE::descriptor + String16("/") + instance);
196 }
197 
198 template<typename INTERFACE>
199 sp<INTERFACE> checkVintfService(
200         const String16& instance = String16("default")) {
201     return checkDeclaredService<INTERFACE>(
202         INTERFACE::descriptor + String16("/") + instance);
203 }
204 
205 template<typename INTERFACE>
getService(const String16 & name,sp<INTERFACE> * outService)206 status_t getService(const String16& name, sp<INTERFACE>* outService)
207 {
208     const sp<IServiceManager> sm = defaultServiceManager();
209     if (sm != nullptr) {
210 #pragma clang diagnostic push
211 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
212         *outService = interface_cast<INTERFACE>(sm->getService(name));
213 #pragma clang diagnostic pop // getService deprecation
214         if ((*outService) != nullptr) return NO_ERROR;
215     }
216     return NAME_NOT_FOUND;
217 }
218 
219 LIBBINDER_EXPORTED void* openDeclaredPassthroughHal(const String16& interface,
220                                                     const String16& instance, int flag);
221 
222 LIBBINDER_EXPORTED bool checkCallingPermission(const String16& permission);
223 LIBBINDER_EXPORTED bool checkCallingPermission(const String16& permission, int32_t* outPid,
224                                                int32_t* outUid);
225 LIBBINDER_EXPORTED bool checkPermission(const String16& permission, pid_t pid, uid_t uid,
226                                         bool logPermissionFailure = true);
227 
228 // ----------------------------------------------------------------------
229 // Trusty's definition of the socket APIs does not include sockaddr types
230 #ifndef __TRUSTY__
231 typedef std::function<status_t(const String16& name, sockaddr* outAddr, socklen_t addrSize)>
232         RpcSocketAddressProvider;
233 
234 /**
235  * This callback provides a way for clients to get access to remote services by
236  * providing an Accessor object from libbinder that can connect to the remote
237  * service over sockets.
238  *
239  * \param instance name of the service that the callback will provide an
240  *        Accessor for. The provided accessor will be used to set up a client
241  *        RPC connection in libbinder in order to return a binder for the
242  *        associated remote service.
243  *
244  * \return IBinder of the Accessor object that libbinder implements.
245  *         nullptr if the provider callback doesn't know how to reach the
246  *         service or doesn't want to provide access for any other reason.
247  */
248 typedef std::function<sp<IBinder>(const String16& instance)> RpcAccessorProvider;
249 
250 class AccessorProvider;
251 
252 /**
253  * Register a RpcAccessorProvider for the service manager APIs.
254  *
255  * \param instances that the RpcAccessorProvider knows about and can provide an
256  *        Accessor for.
257  * \param provider callback that generates Accessors.
258  *
259  * \return A pointer used as a recept for the successful addition of the
260  *         AccessorProvider. This is needed to unregister it later.
261  */
262 [[nodiscard]] LIBBINDER_EXPORTED std::weak_ptr<AccessorProvider> addAccessorProvider(
263         std::set<std::string>&& instances, RpcAccessorProvider&& providerCallback);
264 
265 /**
266  * Remove an accessor provider using the pointer provided by addAccessorProvider
267  * along with the cookie pointer that was used.
268  *
269  * \param provider cookie that was returned by addAccessorProvider to keep track
270  *        of this instance.
271  */
272 [[nodiscard]] LIBBINDER_EXPORTED status_t
273 removeAccessorProvider(std::weak_ptr<AccessorProvider> provider);
274 
275 /**
276  * Create an Accessor associated with a service that can create a socket connection based
277  * on the connection info from the supplied RpcSocketAddressProvider.
278  *
279  * \param instance name of the service that this Accessor is associated with
280  * \param connectionInfoProvider a callback that returns connection info for
281  *        connecting to the service.
282  * \return the binder of the IAccessor implementation from libbinder
283  */
284 LIBBINDER_EXPORTED sp<IBinder> createAccessor(const String16& instance,
285                                               RpcSocketAddressProvider&& connectionInfoProvider);
286 
287 /**
288  * Check to make sure this binder is the expected binder that is an IAccessor
289  * associated with a specific instance.
290  *
291  * This helper function exists to avoid adding the IAccessor type to
292  * libbinder_ndk.
293  *
294  * \param instance name of the service that this Accessor should be associated with
295  * \param binder to validate
296  *
297  * \return OK if the binder is an IAccessor for `instance`
298  */
299 LIBBINDER_EXPORTED status_t validateAccessor(const String16& instance, const sp<IBinder>& binder);
300 
301 /**
302  * Have libbinder wrap this IAccessor binder in an IAccessorDelegator and return
303  * it.
304  *
305  * This is required only in very specific situations when the process that has
306  * permissions to connect the to RPC service's socket and create the FD for it
307  * is in a separate process from this process that wants to service the Accessor
308  * binder and the communication between these two processes is binder RPC. This
309  * is needed because the binder passed over the binder RPC connection can not be
310  * used as a kernel binder, and needs to be wrapped by a kernel binder that can
311  * then be registered with service manager.
312  *
313  * \param instance name of the Accessor.
314  * \param binder to wrap in a Delegator and register with service manager.
315  * \param outDelegator the wrapped kernel binder for IAccessorDelegator
316  *
317  * \return OK if the binder is an IAccessor for `instance` and the delegator was
318  * successfully created.
319  */
320 LIBBINDER_EXPORTED status_t delegateAccessor(const String16& name, const sp<IBinder>& accessor,
321                                              sp<IBinder>* delegator);
322 #endif // __TRUSTY__
323 
324 #ifndef __ANDROID__
325 // Create an IServiceManager that delegates the service manager on the device via adb.
326 // This is can be set as the default service manager at program start, so that
327 // defaultServiceManager() returns it:
328 //    int main() {
329 //        setDefaultServiceManager(createRpcDelegateServiceManager());
330 //        auto sm = defaultServiceManager();
331 //        // ...
332 //    }
333 // Resources are cleaned up when the object is destroyed.
334 //
335 // For each returned binder object, at most |maxOutgoingConnections| outgoing connections are
336 // instantiated, depending on how many the service on the device is configured with.
337 // Hence, only |maxOutgoingConnections| calls can be made simultaneously.
338 // See also RpcSession::setMaxOutgoingConnections.
339 struct RpcDelegateServiceManagerOptions {
340     std::optional<size_t> maxOutgoingConnections;
341 };
342 LIBBINDER_EXPORTED sp<IServiceManager> createRpcDelegateServiceManager(
343         const RpcDelegateServiceManagerOptions& options);
344 #endif
345 
346 } // namespace android
347