/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.net.nsd; import android.annotation.NonNull; import android.annotation.Nullable; import android.annotation.RequiresPermission; import android.annotation.SdkConstant; import android.annotation.SdkConstant.SdkConstantType; import android.annotation.SystemService; import android.app.compat.CompatChanges; import android.compat.annotation.ChangeId; import android.compat.annotation.EnabledSince; import android.content.Context; import android.net.ConnectivityManager; import android.net.ConnectivityManager.NetworkCallback; import android.net.Network; import android.net.NetworkRequest; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; import android.os.RemoteException; import android.text.TextUtils; import android.util.ArrayMap; import android.util.ArraySet; import android.util.Log; import android.util.SparseArray; import com.android.internal.annotations.GuardedBy; import com.android.internal.annotations.VisibleForTesting; import java.util.Objects; import java.util.concurrent.Executor; /** * The Network Service Discovery Manager class provides the API to discover services * on a network. As an example, if device A and device B are connected over a Wi-Fi * network, a game registered on device A can be discovered by a game on device * B. Another example use case is an application discovering printers on the network. * *
The API currently supports DNS based service discovery and discovery is currently * limited to a local network over Multicast DNS. DNS service discovery is described at * http://files.dns-sd.org/draft-cheshire-dnsext-dns-sd.txt * *
The API is asynchronous, and responses to requests from an application are on listener * callbacks on a separate internal thread. * *
There are three main operations the API supports - registration, discovery and resolution. *
* Application start * | * | * | onServiceRegistered() * Register any local services / * to be advertised with \ * registerService() onRegistrationFailed() * | * | * discoverServices() * | * Maintain a list to track * discovered services * | * |---------> * | | * | onServiceFound() * | | * | add service to list * | | * |<---------- * | * |---------> * | | * | onServiceLost() * | | * | remove service from list * | | * |<---------- * | * | * | Connect to a service * | from list ? * | * resolveService() * | * onServiceResolved() * | * Establish connection to service * with the host and port information * ** An application that needs to advertise itself over a network for other applications to * discover it can do so with a call to {@link #registerService}. If Example is a http based * application that can provide HTML data to peer services, it can register a name "Example" * with service type "_http._tcp". A successful registration is notified with a callback to * {@link RegistrationListener#onServiceRegistered} and a failure to register is notified * over {@link RegistrationListener#onRegistrationFailed} * *
A peer application looking for http services can initiate a discovery for "_http._tcp" * with a call to {@link #discoverServices}. A service found is notified with a callback * to {@link DiscoveryListener#onServiceFound} and a service lost is notified on * {@link DiscoveryListener#onServiceLost}. * *
Once the peer application discovers the "Example" http service, and either needs to read the
* attributes of the service or wants to receive data from the "Example" application, it can
* initiate a resolve with {@link #resolveService} to resolve the attributes, host, and port
* details. A successful resolve is notified on {@link ResolveListener#onServiceResolved} and a
* failure is notified on {@link ResolveListener#onResolveFailed}.
*
* Applications can reserve for a service type at
* http://www.iana.org/form/ports-service. Existing services can be found at
* http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xml
*
* {@see NsdServiceInfo}
*/
@SystemService(Context.NSD_SERVICE)
public final class NsdManager {
private static final String TAG = NsdManager.class.getSimpleName();
private static final boolean DBG = false;
/**
* When enabled, apps targeting < Android 12 are considered legacy for
* the NSD native daemon.
* The platform will only keep the daemon running as long as there are
* any legacy apps connected.
*
* After Android 12, directly communicate with native daemon might not
* work since the native damon won't always stay alive.
* Use the NSD APIs from NsdManager as the replacement is recommended.
* An another alternative could be bundling your own mdns solutions instead of
* depending on the system mdns native daemon.
*
* @hide
*/
@ChangeId
@EnabledSince(targetSdkVersion = android.os.Build.VERSION_CODES.S)
public static final long RUN_NATIVE_NSD_ONLY_IF_LEGACY_APPS = 191844585L;
/**
* Broadcast intent action to indicate whether network service discovery is
* enabled or disabled. An extra {@link #EXTRA_NSD_STATE} provides the state
* information as int.
*
* @see #EXTRA_NSD_STATE
*/
@SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
public static final String ACTION_NSD_STATE_CHANGED = "android.net.nsd.STATE_CHANGED";
/**
* The lookup key for an int that indicates whether network service discovery is enabled
* or disabled. Retrieve it with {@link android.content.Intent#getIntExtra(String,int)}.
*
* @see #NSD_STATE_DISABLED
* @see #NSD_STATE_ENABLED
*/
public static final String EXTRA_NSD_STATE = "nsd_state";
/**
* Network service discovery is disabled
*
* @see #ACTION_NSD_STATE_CHANGED
*/
public static final int NSD_STATE_DISABLED = 1;
/**
* Network service discovery is enabled
*
* @see #ACTION_NSD_STATE_CHANGED
*/
public static final int NSD_STATE_ENABLED = 2;
/** @hide */
public static final int DISCOVER_SERVICES = 1;
/** @hide */
public static final int DISCOVER_SERVICES_STARTED = 2;
/** @hide */
public static final int DISCOVER_SERVICES_FAILED = 3;
/** @hide */
public static final int SERVICE_FOUND = 4;
/** @hide */
public static final int SERVICE_LOST = 5;
/** @hide */
public static final int STOP_DISCOVERY = 6;
/** @hide */
public static final int STOP_DISCOVERY_FAILED = 7;
/** @hide */
public static final int STOP_DISCOVERY_SUCCEEDED = 8;
/** @hide */
public static final int REGISTER_SERVICE = 9;
/** @hide */
public static final int REGISTER_SERVICE_FAILED = 10;
/** @hide */
public static final int REGISTER_SERVICE_SUCCEEDED = 11;
/** @hide */
public static final int UNREGISTER_SERVICE = 12;
/** @hide */
public static final int UNREGISTER_SERVICE_FAILED = 13;
/** @hide */
public static final int UNREGISTER_SERVICE_SUCCEEDED = 14;
/** @hide */
public static final int RESOLVE_SERVICE = 15;
/** @hide */
public static final int RESOLVE_SERVICE_FAILED = 16;
/** @hide */
public static final int RESOLVE_SERVICE_SUCCEEDED = 17;
/** @hide */
public static final int DAEMON_CLEANUP = 18;
/** @hide */
public static final int DAEMON_STARTUP = 19;
/** @hide */
public static final int ENABLE = 20;
/** @hide */
public static final int DISABLE = 21;
/** @hide */
public static final int MDNS_SERVICE_EVENT = 22;
/** @hide */
public static final int REGISTER_CLIENT = 23;
/** @hide */
public static final int UNREGISTER_CLIENT = 24;
/** Dns based service discovery protocol */
public static final int PROTOCOL_DNS_SD = 0x0001;
private static final SparseArray The function call immediately returns after sending a request to register service
* to the framework. The application is notified of a successful registration
* through the callback {@link RegistrationListener#onServiceRegistered} or a failure
* through {@link RegistrationListener#onRegistrationFailed}.
*
* The application should call {@link #unregisterService} when the service
* registration is no longer required, and/or whenever the application is stopped.
*
* @param serviceInfo The service being registered
* @param protocolType The service discovery protocol
* @param listener The listener notifies of a successful registration and is used to
* unregister this service through a call on {@link #unregisterService}. Cannot be null.
* Cannot be in use for an active service registration.
*/
public void registerService(NsdServiceInfo serviceInfo, int protocolType,
RegistrationListener listener) {
registerService(serviceInfo, protocolType, Runnable::run, listener);
}
/**
* Register a service to be discovered by other services.
*
* The function call immediately returns after sending a request to register service
* to the framework. The application is notified of a successful registration
* through the callback {@link RegistrationListener#onServiceRegistered} or a failure
* through {@link RegistrationListener#onRegistrationFailed}.
*
* The application should call {@link #unregisterService} when the service
* registration is no longer required, and/or whenever the application is stopped.
* @param serviceInfo The service being registered
* @param protocolType The service discovery protocol
* @param executor Executor to run listener callbacks with
* @param listener The listener notifies of a successful registration and is used to
* unregister this service through a call on {@link #unregisterService}. Cannot be null.
*/
public void registerService(@NonNull NsdServiceInfo serviceInfo, int protocolType,
@NonNull Executor executor, @NonNull RegistrationListener listener) {
if (serviceInfo.getPort() <= 0) {
throw new IllegalArgumentException("Invalid port number");
}
checkServiceInfo(serviceInfo);
checkProtocol(protocolType);
int key = putListener(listener, executor, serviceInfo);
try {
mService.registerService(key, serviceInfo);
} catch (RemoteException e) {
e.rethrowFromSystemServer();
}
}
/**
* Unregister a service registered through {@link #registerService}. A successful
* unregister is notified to the application with a call to
* {@link RegistrationListener#onServiceUnregistered}.
*
* @param listener This should be the listener object that was passed to
* {@link #registerService}. It identifies the service that should be unregistered
* and notifies of a successful or unsuccessful unregistration via the listener
* callbacks. In API versions 20 and above, the listener object may be used for
* another service registration once the callback has been called. In API versions <= 19,
* there is no entirely reliable way to know when a listener may be re-used, and a new
* listener should be created for each service registration request.
*/
public void unregisterService(RegistrationListener listener) {
int id = getListenerKey(listener);
try {
mService.unregisterService(id);
} catch (RemoteException e) {
e.rethrowFromSystemServer();
}
}
/**
* Initiate service discovery to browse for instances of a service type. Service discovery
* consumes network bandwidth and will continue until the application calls
* {@link #stopServiceDiscovery}.
*
* The function call immediately returns after sending a request to start service
* discovery to the framework. The application is notified of a success to initiate
* discovery through the callback {@link DiscoveryListener#onDiscoveryStarted} or a failure
* through {@link DiscoveryListener#onStartDiscoveryFailed}.
*
* Upon successful start, application is notified when a service is found with
* {@link DiscoveryListener#onServiceFound} or when a service is lost with
* {@link DiscoveryListener#onServiceLost}.
*
* Upon failure to start, service discovery is not active and application does
* not need to invoke {@link #stopServiceDiscovery}
*
* The application should call {@link #stopServiceDiscovery} when discovery of this
* service type is no longer required, and/or whenever the application is paused or
* stopped.
*
* @param serviceType The service type being discovered. Examples include "_http._tcp" for
* http services or "_ipp._tcp" for printers
* @param protocolType The service discovery protocol
* @param listener The listener notifies of a successful discovery and is used
* to stop discovery on this serviceType through a call on {@link #stopServiceDiscovery}.
* Cannot be null. Cannot be in use for an active service discovery.
*/
public void discoverServices(String serviceType, int protocolType, DiscoveryListener listener) {
discoverServices(serviceType, protocolType, (Network) null, Runnable::run, listener);
}
/**
* Initiate service discovery to browse for instances of a service type. Service discovery
* consumes network bandwidth and will continue until the application calls
* {@link #stopServiceDiscovery}.
*
* The function call immediately returns after sending a request to start service
* discovery to the framework. The application is notified of a success to initiate
* discovery through the callback {@link DiscoveryListener#onDiscoveryStarted} or a failure
* through {@link DiscoveryListener#onStartDiscoveryFailed}.
*
* Upon successful start, application is notified when a service is found with
* {@link DiscoveryListener#onServiceFound} or when a service is lost with
* {@link DiscoveryListener#onServiceLost}.
*
* Upon failure to start, service discovery is not active and application does
* not need to invoke {@link #stopServiceDiscovery}
*
* The application should call {@link #stopServiceDiscovery} when discovery of this
* service type is no longer required, and/or whenever the application is paused or
* stopped.
* @param serviceType The service type being discovered. Examples include "_http._tcp" for
* http services or "_ipp._tcp" for printers
* @param protocolType The service discovery protocol
* @param network Network to discover services on, or null to discover on all available networks
* @param executor Executor to run listener callbacks with
* @param listener The listener notifies of a successful discovery and is used
* to stop discovery on this serviceType through a call on {@link #stopServiceDiscovery}.
*/
public void discoverServices(@NonNull String serviceType, int protocolType,
@Nullable Network network, @NonNull Executor executor,
@NonNull DiscoveryListener listener) {
if (TextUtils.isEmpty(serviceType)) {
throw new IllegalArgumentException("Service type cannot be empty");
}
checkProtocol(protocolType);
NsdServiceInfo s = new NsdServiceInfo();
s.setServiceType(serviceType);
s.setNetwork(network);
int key = putListener(listener, executor, s);
try {
mService.discoverServices(key, s);
} catch (RemoteException e) {
e.rethrowFromSystemServer();
}
}
/**
* Initiate service discovery to browse for instances of a service type. Service discovery
* consumes network bandwidth and will continue until the application calls
* {@link #stopServiceDiscovery}.
*
* The function call immediately returns after sending a request to start service
* discovery to the framework. The application is notified of a success to initiate
* discovery through the callback {@link DiscoveryListener#onDiscoveryStarted} or a failure
* through {@link DiscoveryListener#onStartDiscoveryFailed}.
*
* Upon successful start, application is notified when a service is found with
* {@link DiscoveryListener#onServiceFound} or when a service is lost with
* {@link DiscoveryListener#onServiceLost}.
*
* Upon failure to start, service discovery is not active and application does
* not need to invoke {@link #stopServiceDiscovery}
*
* The application should call {@link #stopServiceDiscovery} when discovery of this
* service type is no longer required, and/or whenever the application is paused or
* stopped.
*
* During discovery, new networks may connect or existing networks may disconnect - for
* example if wifi is reconnected. When a service was found on a network that disconnects,
* {@link DiscoveryListener#onServiceLost} will be called. If a new network connects that
* matches the {@link NetworkRequest}, {@link DiscoveryListener#onServiceFound} will be called
* for services found on that network. Applications that do not want to track networks
* themselves are encouraged to use this method instead of other overloads of
* {@code discoverServices}, as they will receive proper notifications when a service becomes
* available or unavailable due to network changes.
* @param serviceType The service type being discovered. Examples include "_http._tcp" for
* http services or "_ipp._tcp" for printers
* @param protocolType The service discovery protocol
* @param networkRequest Request specifying networks that should be considered when discovering
* @param executor Executor to run listener callbacks with
* @param listener The listener notifies of a successful discovery and is used
* to stop discovery on this serviceType through a call on {@link #stopServiceDiscovery}.
*/
@RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
public void discoverServices(@NonNull String serviceType, int protocolType,
@NonNull NetworkRequest networkRequest, @NonNull Executor executor,
@NonNull DiscoveryListener listener) {
if (TextUtils.isEmpty(serviceType)) {
throw new IllegalArgumentException("Service type cannot be empty");
}
Objects.requireNonNull(networkRequest, "NetworkRequest cannot be null");
checkProtocol(protocolType);
NsdServiceInfo s = new NsdServiceInfo();
s.setServiceType(serviceType);
final int baseListenerKey = putListener(listener, executor, s);
final PerNetworkDiscoveryTracker discoveryInfo = new PerNetworkDiscoveryTracker(
serviceType, protocolType, executor, listener);
synchronized (mPerNetworkDiscoveryMap) {
mPerNetworkDiscoveryMap.put(baseListenerKey, discoveryInfo);
discoveryInfo.start(networkRequest);
}
}
/**
* Stop service discovery initiated with {@link #discoverServices}. An active service
* discovery is notified to the application with {@link DiscoveryListener#onDiscoveryStarted}
* and it stays active until the application invokes a stop service discovery. A successful
* stop is notified to with a call to {@link DiscoveryListener#onDiscoveryStopped}.
*
* Upon failure to stop service discovery, application is notified through
* {@link DiscoveryListener#onStopDiscoveryFailed}.
*
* @param listener This should be the listener object that was passed to {@link #discoverServices}.
* It identifies the discovery that should be stopped and notifies of a successful or
* unsuccessful stop. In API versions 20 and above, the listener object may be used for
* another service discovery once the callback has been called. In API versions <= 19,
* there is no entirely reliable way to know when a listener may be re-used, and a new
* listener should be created for each service discovery request.
*/
public void stopServiceDiscovery(DiscoveryListener listener) {
int id = getListenerKey(listener);
// If this is a PerNetworkDiscovery request, handle it as such
synchronized (mPerNetworkDiscoveryMap) {
final PerNetworkDiscoveryTracker info = mPerNetworkDiscoveryMap.get(id);
if (info != null) {
info.requestStop();
return;
}
}
try {
mService.stopDiscovery(id);
} catch (RemoteException e) {
e.rethrowFromSystemServer();
}
}
/**
* Resolve a discovered service. An application can resolve a service right before
* establishing a connection to fetch the IP and port details on which to setup
* the connection.
*
* @param serviceInfo service to be resolved
* @param listener to receive callback upon success or failure. Cannot be null.
* Cannot be in use for an active service resolution.
*/
public void resolveService(NsdServiceInfo serviceInfo, ResolveListener listener) {
resolveService(serviceInfo, Runnable::run, listener);
}
/**
* Resolve a discovered service. An application can resolve a service right before
* establishing a connection to fetch the IP and port details on which to setup
* the connection.
* @param serviceInfo service to be resolved
* @param executor Executor to run listener callbacks with
* @param listener to receive callback upon success or failure.
*/
public void resolveService(@NonNull NsdServiceInfo serviceInfo,
@NonNull Executor executor, @NonNull ResolveListener listener) {
checkServiceInfo(serviceInfo);
int key = putListener(listener, executor, serviceInfo);
try {
mService.resolveService(key, serviceInfo);
} catch (RemoteException e) {
e.rethrowFromSystemServer();
}
}
private static void checkListener(Object listener) {
Objects.requireNonNull(listener, "listener cannot be null");
}
private static void checkProtocol(int protocolType) {
if (protocolType != PROTOCOL_DNS_SD) {
throw new IllegalArgumentException("Unsupported protocol");
}
}
private static void checkServiceInfo(NsdServiceInfo serviceInfo) {
Objects.requireNonNull(serviceInfo, "NsdServiceInfo cannot be null");
if (TextUtils.isEmpty(serviceInfo.getServiceName())) {
throw new IllegalArgumentException("Service name cannot be empty");
}
if (TextUtils.isEmpty(serviceInfo.getServiceType())) {
throw new IllegalArgumentException("Service type cannot be empty");
}
}
}