[mdns] service-side impl for custom host
This CL adds the service-side implementation of the custom host support
added in aosp/2890957.
Bug: 284904661
Bug: 320838284
Test: atest CtsNetTestCases FrameworksNetTests
Change-Id: I92c774ead4778870ff7358ccb28d6ad6e266f1b5
diff --git a/service-t/src/com/android/server/NsdService.java b/service-t/src/com/android/server/NsdService.java
index 0feda6e..e10ba52 100644
--- a/service-t/src/com/android/server/NsdService.java
+++ b/service-t/src/com/android/server/NsdService.java
@@ -895,10 +895,18 @@
serviceType);
final String registerServiceType = typeSubtype == null
? null : typeSubtype.first;
+ final String hostname = serviceInfo.getHostname();
+ // Keep compatible with the legacy behavior: It's allowed to set host
+ // addresses for a service registration although the host addresses
+ // won't be registered. To register the addresses for a host, the
+ // hostname must be specified.
+ if (hostname == null) {
+ serviceInfo.setHostAddresses(Collections.emptyList());
+ }
if (clientInfo.mUseJavaBackend
|| mDeps.isMdnsAdvertiserEnabled(mContext)
|| useAdvertiserForType(registerServiceType)) {
- if (registerServiceType == null) {
+ if (serviceType != null && registerServiceType == null) {
Log.e(TAG, "Invalid service type: " + serviceType);
clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
@@ -921,14 +929,25 @@
} else {
transactionId = getUniqueId();
}
- serviceInfo.setServiceType(registerServiceType);
- serviceInfo.setServiceName(truncateServiceName(
- serviceInfo.getServiceName()));
+
+ if (registerServiceType != null) {
+ serviceInfo.setServiceType(registerServiceType);
+ serviceInfo.setServiceName(
+ truncateServiceName(serviceInfo.getServiceName()));
+ }
+
+ if (!checkHostname(hostname)) {
+ clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
+ NsdManager.FAILURE_BAD_PARAMETERS, false /* isLegacy */);
+ break;
+ }
Set<String> subtypes = new ArraySet<>(serviceInfo.getSubtypes());
- for (String subType: typeSubtype.second) {
- if (!TextUtils.isEmpty(subType)) {
- subtypes.add(subType);
+ if (typeSubtype != null && typeSubtype.second != null) {
+ for (String subType : typeSubtype.second) {
+ if (!TextUtils.isEmpty(subType)) {
+ subtypes.add(subType);
+ }
}
}
subtypes = dedupSubtypeLabels(subtypes);
@@ -945,7 +964,7 @@
MdnsAdvertisingOptions.newBuilder().setIsOnlyUpdate(
isUpdateOnly).build();
mAdvertiser.addOrUpdateService(transactionId, serviceInfo,
- mdnsAdvertisingOptions);
+ mdnsAdvertisingOptions, clientInfo.mUid);
storeAdvertiserRequestMap(clientRequestId, transactionId, clientInfo,
serviceInfo.getNetwork());
} else {
@@ -1535,6 +1554,7 @@
Log.e(TAG, "Invalid attribute", e);
}
}
+ info.setHostname(getHostname(serviceInfo));
final List<InetAddress> addresses = getInetAddresses(serviceInfo);
if (addresses.size() != 0) {
info.setHostAddresses(addresses);
@@ -1571,6 +1591,7 @@
}
}
+ info.setHostname(getHostname(serviceInfo));
final List<InetAddress> addresses = getInetAddresses(serviceInfo);
info.setHostAddresses(addresses);
clientInfo.onServiceUpdated(clientRequestId, info, request);
@@ -1617,6 +1638,16 @@
return addresses;
}
+ @NonNull
+ private static String getHostname(@NonNull MdnsServiceInfo serviceInfo) {
+ String[] hostname = serviceInfo.getHostName();
+ // Strip the "local" top-level domain.
+ if (hostname.length >= 2 && hostname[hostname.length - 1].equals("local")) {
+ hostname = Arrays.copyOf(hostname, hostname.length - 1);
+ }
+ return String.join(".", hostname);
+ }
+
private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
switch (netId) {
case NETID_UNSET:
@@ -1702,6 +1733,21 @@
return new Pair<>(queryType, Collections.emptyList());
}
+ /**
+ * Checks if the hostname is valid.
+ *
+ * <p>For now NsdService only allows single-label hostnames conforming to RFC 1035. In other
+ * words, the hostname should be at most 63 characters long and it only contains letters, digits
+ * and hyphens.
+ */
+ public static boolean checkHostname(@Nullable String hostname) {
+ if (hostname == null) {
+ return true;
+ }
+ String HOSTNAME_REGEX = "^[a-zA-Z]([a-zA-Z0-9-_]{0,61}[a-zA-Z0-9])?$";
+ return Pattern.compile(HOSTNAME_REGEX).matcher(hostname).matches();
+ }
+
/** Returns {@code true} if {@code subtype} is a valid DNS-SD subtype label. */
private static boolean checkSubtypeLabel(String subtype) {
return Pattern.compile("^" + TYPE_SUBTYPE_LABEL_REGEX + "$").matcher(subtype).matches();
@@ -2031,9 +2077,10 @@
final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
if (clientRequestId < 0) return;
- // onRegisterServiceSucceeded only has the service name in its info. This aligns with
- // historical behavior.
+ // onRegisterServiceSucceeded only has the service name and hostname in its info. This
+ // aligns with historical behavior.
final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
+ cbInfo.setHostname(registeredInfo.getHostname());
final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
clientInfo.onRegisterServiceSucceeded(clientRequestId, cbInfo, request);
}
@@ -2143,6 +2190,7 @@
@Override
public void registerService(int listenerKey, AdvertisingRequest advertisingRequest)
throws RemoteException {
+ NsdManager.checkServiceInfoForRegistration(advertisingRequest.getServiceInfo());
mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
NsdManager.REGISTER_SERVICE, 0, listenerKey,
new AdvertisingArgs(this, advertisingRequest)
diff --git a/service-t/src/com/android/server/connectivity/mdns/MdnsAdvertiser.java b/service-t/src/com/android/server/connectivity/mdns/MdnsAdvertiser.java
index b2af93c..60859f8 100644
--- a/service-t/src/com/android/server/connectivity/mdns/MdnsAdvertiser.java
+++ b/service-t/src/com/android/server/connectivity/mdns/MdnsAdvertiser.java
@@ -17,6 +17,8 @@
package com.android.server.connectivity.mdns;
import static com.android.server.connectivity.mdns.MdnsConstants.NO_PACKET;
+import static com.android.server.connectivity.mdns.MdnsInterfaceAdvertiser.CONFLICT_HOST;
+import static com.android.server.connectivity.mdns.MdnsInterfaceAdvertiser.CONFLICT_SERVICE;
import static com.android.server.connectivity.mdns.MdnsRecord.MAX_LABEL_LENGTH;
import android.annotation.NonNull;
@@ -31,6 +33,7 @@
import android.net.nsd.OffloadServiceInfo;
import android.os.Build;
import android.os.Looper;
+import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.Log;
import android.util.SparseArray;
@@ -151,7 +154,9 @@
mSharedLog.wtf("Register succeeded for unknown registration");
return;
}
- if (mMdnsFeatureFlags.mIsMdnsOffloadFeatureEnabled) {
+ if (mMdnsFeatureFlags.mIsMdnsOffloadFeatureEnabled
+ // TODO: Enable offload when the serviceInfo contains a custom host.
+ && TextUtils.isEmpty(registration.getServiceInfo().getHostname())) {
final String interfaceName = advertiser.getSocketInterfaceName();
final List<OffloadServiceInfoWrapper> existingOffloadServiceInfoWrappers =
mInterfaceOffloadServices.computeIfAbsent(interfaceName,
@@ -179,8 +184,11 @@
}
@Override
- public void onServiceConflict(@NonNull MdnsInterfaceAdvertiser advertiser, int serviceId) {
- mSharedLog.i("Found conflict, restarted probing for service " + serviceId);
+ public void onServiceConflict(@NonNull MdnsInterfaceAdvertiser advertiser, int serviceId,
+ int conflictType) {
+ mSharedLog.i("Found conflict, restarted probing for service "
+ + serviceId + " "
+ + conflictType);
final Registration registration = mRegistrations.get(serviceId);
if (registration == null) return;
@@ -205,10 +213,22 @@
return;
}
- // Conflict was found during probing; rename once to find a name that has no conflict
- registration.updateForConflict(
- registration.makeNewServiceInfoForConflict(1 /* renameCount */),
- 1 /* renameCount */);
+ if ((conflictType & CONFLICT_SERVICE) != 0) {
+ // Service conflict was found during probing; rename once to find a name that has no
+ // conflict
+ registration.updateForServiceConflict(
+ registration.makeNewServiceInfoForServiceConflict(1 /* renameCount */),
+ 1 /* renameCount */);
+ }
+
+ if ((conflictType & CONFLICT_HOST) != 0) {
+ // Host conflict was found during probing; rename once to find a name that has no
+ // conflict
+ registration.updateForHostConflict(
+ registration.makeNewServiceInfoForHostConflict(1 /* renameCount */),
+ 1 /* renameCount */);
+ }
+
registration.mConflictDuringProbingCount++;
// Keep renaming if the new name conflicts in local registrations
@@ -231,23 +251,53 @@
}
};
- private boolean hasAnyConflict(
+ private boolean hasAnyServiceConflict(
@NonNull BiPredicate<Network, InterfaceAdvertiserRequest> applicableAdvertiserFilter,
@NonNull NsdServiceInfo newInfo) {
- return any(mAdvertiserRequests, (network, adv) ->
- applicableAdvertiserFilter.test(network, adv) && adv.hasConflict(newInfo));
+ return any(
+ mAdvertiserRequests,
+ (network, adv) ->
+ applicableAdvertiserFilter.test(network, adv)
+ && adv.hasServiceConflict(newInfo));
+ }
+
+ private boolean hasAnyHostConflict(
+ @NonNull BiPredicate<Network, InterfaceAdvertiserRequest> applicableAdvertiserFilter,
+ @NonNull NsdServiceInfo newInfo,
+ int clientUid) {
+ // Check if it conflicts with custom hosts.
+ if (any(
+ mAdvertiserRequests,
+ (network, adv) ->
+ applicableAdvertiserFilter.test(network, adv)
+ && adv.hasHostConflict(newInfo, clientUid))) {
+ return true;
+ }
+ // Check if it conflicts with the default hostname.
+ return MdnsUtils.equalsIgnoreDnsCase(newInfo.getHostname(), mDeviceHostName[0]);
}
private void updateRegistrationUntilNoConflict(
@NonNull BiPredicate<Network, InterfaceAdvertiserRequest> applicableAdvertiserFilter,
@NonNull Registration registration) {
- int renameCount = 0;
NsdServiceInfo newInfo = registration.getServiceInfo();
- while (hasAnyConflict(applicableAdvertiserFilter, newInfo)) {
- renameCount++;
- newInfo = registration.makeNewServiceInfoForConflict(renameCount);
+
+ int renameServiceCount = 0;
+ while (hasAnyServiceConflict(applicableAdvertiserFilter, newInfo)) {
+ renameServiceCount++;
+ newInfo = registration.makeNewServiceInfoForServiceConflict(renameServiceCount);
}
- registration.updateForConflict(newInfo, renameCount);
+ registration.updateForServiceConflict(newInfo, renameServiceCount);
+
+ if (!TextUtils.isEmpty(registration.getServiceInfo().getHostname())) {
+ int renameHostCount = 0;
+ while (hasAnyHostConflict(
+ applicableAdvertiserFilter, newInfo, registration.mClientUid)) {
+ renameHostCount++;
+ newInfo = registration.makeNewServiceInfoForHostConflict(renameHostCount);
+ }
+ registration.updateForHostConflict(newInfo, renameHostCount);
+ }
}
private void maybeSendOffloadStop(final String interfaceName, int serviceId) {
@@ -326,16 +376,27 @@
/**
* Return whether using the proposed new {@link NsdServiceInfo} to add a registration would
- * cause a conflict in this {@link InterfaceAdvertiserRequest}.
+ * cause a conflict of the service in this {@link InterfaceAdvertiserRequest}.
*/
- boolean hasConflict(@NonNull NsdServiceInfo newInfo) {
- return getConflictingService(newInfo) >= 0;
+ boolean hasServiceConflict(@NonNull NsdServiceInfo newInfo) {
+ return getConflictingRegistrationDueToService(newInfo) >= 0;
}
/**
- * Get the ID of a conflicting service, or -1 if none.
+ * Return whether using the proposed new {@link NsdServiceInfo} to add a registration would
+ * cause a conflict of the host in this {@link InterfaceAdvertiserRequest}.
+ *
+ * @param clientUid UID of the user who wants to advertise the serviceInfo.
*/
- int getConflictingService(@NonNull NsdServiceInfo info) {
+ boolean hasHostConflict(@NonNull NsdServiceInfo newInfo, int clientUid) {
+ return getConflictingRegistrationDueToHost(newInfo, clientUid) >= 0;
+ }
+
+ /** Get the ID of a conflicting registration due to service, or -1 if none. */
+ int getConflictingRegistrationDueToService(@NonNull NsdServiceInfo info) {
+ if (TextUtils.isEmpty(info.getServiceName())) {
+ return -1;
+ }
for (int i = 0; i < mPendingRegistrations.size(); i++) {
final NsdServiceInfo other = mPendingRegistrations.valueAt(i).getServiceInfo();
if (MdnsUtils.equalsIgnoreDnsCase(info.getServiceName(), other.getServiceName())
@@ -348,9 +409,34 @@
}
/**
+ * Get the ID of a conflicting registration due to host, or -1 if none.
+ *
+ * <p>It's valid that multiple registrations from the same user are using the same hostname.
+ *
+ * <p>If there's already another registration with the same hostname requested by another
+ * user, this is considered a conflict.
+ */
+ int getConflictingRegistrationDueToHost(@NonNull NsdServiceInfo info, int clientUid) {
+ if (TextUtils.isEmpty(info.getHostname())) {
+ return -1;
+ }
+ for (int i = 0; i < mPendingRegistrations.size(); i++) {
+ final Registration otherRegistration = mPendingRegistrations.valueAt(i);
+ final NsdServiceInfo otherInfo = otherRegistration.getServiceInfo();
+ if (clientUid != otherRegistration.mClientUid
+ && MdnsUtils.equalsIgnoreDnsCase(
+ info.getHostname(), otherInfo.getHostname())) {
+ return mPendingRegistrations.keyAt(i);
+ }
+ }
+ return -1;
+ }
+
+ /**
* Add a service to advertise.
*
- * Conflicts must be checked via {@link #getConflictingService} before attempting to add.
+ * <p>Conflicts must be checked via {@link #getConflictingRegistrationDueToService} and
+ * {@link #getConflictingRegistrationDueToHost} before attempting to add.
*/
void addService(int id, @NonNull Registration registration) {
mPendingRegistrations.put(id, registration);
@@ -484,27 +570,35 @@
}
private static class Registration {
- @NonNull
- final String mOriginalName;
+ @Nullable
+ final String mOriginalServiceName;
+ @Nullable
+ final String mOriginalHostname;
boolean mNotifiedRegistrationSuccess;
- private int mConflictCount;
+ private int mServiceNameConflictCount;
+ private int mHostnameConflictCount;
@NonNull
private NsdServiceInfo mServiceInfo;
+ final int mClientUid;
int mConflictDuringProbingCount;
int mConflictAfterProbingCount;
- private Registration(@NonNull NsdServiceInfo serviceInfo) {
- this.mOriginalName = serviceInfo.getServiceName();
+
+ private Registration(@NonNull NsdServiceInfo serviceInfo, int clientUid) {
+ this.mOriginalServiceName = serviceInfo.getServiceName();
+ this.mOriginalHostname = serviceInfo.getHostname();
this.mServiceInfo = serviceInfo;
+ this.mClientUid = clientUid;
}
- /**
- * Matches between the NsdServiceInfo in the Registration and the provided argument.
- */
- public boolean matches(@Nullable NsdServiceInfo newInfo) {
- return Objects.equals(newInfo.getServiceName(), mOriginalName) && Objects.equals(
- newInfo.getServiceType(), mServiceInfo.getServiceType()) && Objects.equals(
- newInfo.getNetwork(), mServiceInfo.getNetwork());
+ /** Check if the new {@link NsdServiceInfo} doesn't update any data other than subtypes. */
+ public boolean isSubtypeOnlyUpdate(@NonNull NsdServiceInfo newInfo) {
+ return Objects.equals(newInfo.getServiceName(), mOriginalServiceName)
+ && Objects.equals(newInfo.getServiceType(), mServiceInfo.getServiceType())
+ && newInfo.getPort() == mServiceInfo.getPort()
+ && Objects.equals(newInfo.getHostname(), mOriginalHostname)
+ && Objects.equals(newInfo.getHostAddresses(), mServiceInfo.getHostAddresses())
+ && Objects.equals(newInfo.getNetwork(), mServiceInfo.getNetwork());
}
/**
@@ -521,8 +615,19 @@
* @param newInfo New service info to use.
* @param renameCount How many renames were done before reaching the current name.
*/
- private void updateForConflict(@NonNull NsdServiceInfo newInfo, int renameCount) {
- mConflictCount += renameCount;
+ private void updateForServiceConflict(@NonNull NsdServiceInfo newInfo, int renameCount) {
+ mServiceNameConflictCount += renameCount;
+ mServiceInfo = newInfo;
+ }
+
+ /**
+ * Update the registration to use a different host name, after a conflict was found.
+ *
+ * @param newInfo New service info to use.
+ * @param renameCount How many renames were done before reaching the current name.
+ */
+ private void updateForHostConflict(@NonNull NsdServiceInfo newInfo, int renameCount) {
+ mHostnameConflictCount += renameCount;
mServiceInfo = newInfo;
}
@@ -538,7 +643,7 @@
* @param renameCount How much to increase the number suffix for this conflict.
*/
@NonNull
- public NsdServiceInfo makeNewServiceInfoForConflict(int renameCount) {
+ public NsdServiceInfo makeNewServiceInfoForServiceConflict(int renameCount) {
// In case of conflict choose a different service name. After the first conflict use
// "Name (2)", then "Name (3)" etc.
// TODO: use a hidden method in NsdServiceInfo once MdnsAdvertiser is moved to service-t
@@ -547,13 +652,40 @@
return newInfo;
}
+ /**
+ * Make a new hostname for the registration, after a conflict was found.
+ *
+ * <p>If a name conflict was found during probing or because different advertising requests
+ * used the same name, the registration is attempted again with a new name (here using a
+ * number suffix, -1, -2, etc). Registration success is notified once probing succeeds with
+ * a new name.
+ *
+ * @param renameCount How much to increase the number suffix for this conflict.
+ */
+ @NonNull
+ public NsdServiceInfo makeNewServiceInfoForHostConflict(int renameCount) {
+ // In case of conflict choose a different hostname. After the first conflict use
+ // "Name-2", then "Name-3" etc.
+ final NsdServiceInfo newInfo = new NsdServiceInfo(mServiceInfo);
+ newInfo.setHostname(getUpdatedHostname(renameCount));
+ return newInfo;
+ }
+
private String getUpdatedServiceName(int renameCount) {
- final String suffix = " (" + (mConflictCount + renameCount + 1) + ")";
- final String truncatedServiceName = MdnsUtils.truncateServiceName(mOriginalName,
+ final String suffix = " (" + (mServiceNameConflictCount + renameCount + 1) + ")";
+ final String truncatedServiceName = MdnsUtils.truncateServiceName(mOriginalServiceName,
MAX_LABEL_LENGTH - suffix.length());
return truncatedServiceName + suffix;
}
+ private String getUpdatedHostname(int renameCount) {
+ final String suffix = "-" + (mHostnameConflictCount + renameCount + 1);
+ final String truncatedHostname =
+ MdnsUtils.truncateServiceName(
+ mOriginalHostname, MAX_LABEL_LENGTH - suffix.length());
+ return truncatedHostname + suffix;
+ }
+
@NonNull
public NsdServiceInfo getServiceInfo() {
return mServiceInfo;
@@ -681,9 +813,10 @@
* @param id A unique ID for the service.
* @param service The service info to advertise.
* @param advertisingOptions The advertising options.
+ * @param clientUid The UID who wants to advertise the service.
*/
public void addOrUpdateService(int id, NsdServiceInfo service,
- MdnsAdvertisingOptions advertisingOptions) {
+ MdnsAdvertisingOptions advertisingOptions, int clientUid) {
checkThread();
final Registration existingRegistration = mRegistrations.get(id);
final Network network = service.getNetwork();
@@ -695,7 +828,7 @@
mCb.onRegisterServiceFailed(id, NsdManager.FAILURE_INTERNAL_ERROR);
return;
}
- if (!(existingRegistration.matches(service))) {
+ if (!(existingRegistration.isSubtypeOnlyUpdate(service))) {
mSharedLog.e("Update request can only update subType, serviceInfo: " + service
+ ", existing serviceInfo: " + existingRegistration.getServiceInfo());
mCb.onRegisterServiceFailed(id, NsdManager.FAILURE_INTERNAL_ERROR);
@@ -715,7 +848,7 @@
}
mSharedLog.i("Adding service " + service + " with ID " + id + " and subtypes "
+ subtypes + " advertisingOptions " + advertisingOptions);
- registration = new Registration(service);
+ registration = new Registration(service, clientUid);
final BiPredicate<Network, InterfaceAdvertiserRequest> checkConflictFilter;
if (network == null) {
// If registering on all networks, no advertiser must have conflicts
diff --git a/service-t/src/com/android/server/connectivity/mdns/MdnsInterfaceAdvertiser.java b/service-t/src/com/android/server/connectivity/mdns/MdnsInterfaceAdvertiser.java
index 730bd7e..f1deab0 100644
--- a/service-t/src/com/android/server/connectivity/mdns/MdnsInterfaceAdvertiser.java
+++ b/service-t/src/com/android/server/connectivity/mdns/MdnsInterfaceAdvertiser.java
@@ -22,10 +22,12 @@
import android.annotation.Nullable;
import android.annotation.RequiresApi;
import android.net.LinkAddress;
+import android.net.nsd.NsdManager;
import android.net.nsd.NsdServiceInfo;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
+import android.util.ArraySet;
import com.android.internal.annotations.VisibleForTesting;
import com.android.net.module.util.HexDump;
@@ -37,6 +39,7 @@
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.List;
+import java.util.Map;
import java.util.Set;
/**
@@ -44,6 +47,9 @@
*/
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
public class MdnsInterfaceAdvertiser implements MulticastPacketReader.PacketHandler {
+ public static final int CONFLICT_SERVICE = 1 << 0;
+ public static final int CONFLICT_HOST = 1 << 1;
+
private static final boolean DBG = MdnsAdvertiser.DBG;
@VisibleForTesting
public static final long EXIT_ANNOUNCEMENT_DELAY_MS = 100L;
@@ -85,10 +91,15 @@
/**
* Called by the advertiser when a conflict was found, during or after probing.
*
- * If a conflict is found during probing, the {@link #renameServiceForConflict} must be
+ * <p>If a conflict is found during probing, the {@link #renameServiceForConflict} must be
* called to restart probing and attempt registration with a different name.
+ *
+ * <p>{@code conflictType} is a bitmap telling which part of the service is conflicting. See
+ * {@link MdnsInterfaceAdvertiser#CONFLICT_SERVICE} and {@link
+ * MdnsInterfaceAdvertiser#CONFLICT_HOST}.
*/
- void onServiceConflict(@NonNull MdnsInterfaceAdvertiser advertiser, int serviceId);
+ void onServiceConflict(
+ @NonNull MdnsInterfaceAdvertiser advertiser, int serviceId, int conflictType);
/**
* Called by the advertiser when it destroyed itself.
@@ -384,8 +395,16 @@
+ packet.additionalRecords.size() + " additional from " + srcCopy);
}
- for (int conflictServiceId : mRecordRepository.getConflictingServices(packet)) {
- mCbHandler.post(() -> mCb.onServiceConflict(this, conflictServiceId));
+ Map<Integer, Integer> conflictingServices =
+ mRecordRepository.getConflictingServices(packet);
+
+ for (Map.Entry<Integer, Integer> entry : conflictingServices.entrySet()) {
+ int serviceId = entry.getKey();
+ int conflictType = entry.getValue();
+ mCbHandler.post(
+ () -> {
+ mCb.onServiceConflict(this, serviceId, conflictType);
+ });
}
// Even in case of conflict, add replies for other services. But in general conflicts would
diff --git a/service-t/src/com/android/server/connectivity/mdns/MdnsRecordRepository.java b/service-t/src/com/android/server/connectivity/mdns/MdnsRecordRepository.java
index 78c3082..fb45454 100644
--- a/service-t/src/com/android/server/connectivity/mdns/MdnsRecordRepository.java
+++ b/service-t/src/com/android/server/connectivity/mdns/MdnsRecordRepository.java
@@ -19,6 +19,8 @@
import static com.android.server.connectivity.mdns.MdnsConstants.IPV4_SOCKET_ADDR;
import static com.android.server.connectivity.mdns.MdnsConstants.IPV6_SOCKET_ADDR;
import static com.android.server.connectivity.mdns.MdnsConstants.NO_PACKET;
+import static com.android.server.connectivity.mdns.MdnsInterfaceAdvertiser.CONFLICT_HOST;
+import static com.android.server.connectivity.mdns.MdnsInterfaceAdvertiser.CONFLICT_SERVICE;
import android.annotation.NonNull;
import android.annotation.Nullable;
@@ -28,6 +30,8 @@
import android.os.Build;
import android.os.Looper;
import android.os.SystemClock;
+import android.text.TextUtils;
+import android.util.ArrayMap;
import android.util.ArraySet;
import android.util.SparseArray;
@@ -54,6 +58,8 @@
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
/**
* A repository of records advertised through {@link MdnsInterfaceAdvertiser}.
@@ -158,11 +164,13 @@
public final List<RecordInfo<?>> allRecords;
@NonNull
public final List<RecordInfo<MdnsPointerRecord>> ptrRecords;
- @NonNull
+ @Nullable
public final RecordInfo<MdnsServiceRecord> srvRecord;
- @NonNull
+ @Nullable
public final RecordInfo<MdnsTextRecord> txtRecord;
@NonNull
+ public final List<RecordInfo<MdnsInetAddressRecord>> addressRecords;
+ @NonNull
public final NsdServiceInfo serviceInfo;
/**
@@ -202,65 +210,96 @@
int repliedServiceCount, int sentPacketCount, boolean exiting, boolean isProbing) {
this.serviceInfo = serviceInfo;
- final String[] serviceType = splitServiceType(serviceInfo);
- final String[] serviceName = splitFullyQualifiedName(serviceInfo, serviceType);
+ final boolean hasService = !TextUtils.isEmpty(serviceInfo.getServiceType());
+ final boolean hasCustomHost = !TextUtils.isEmpty(serviceInfo.getHostname());
+ final String[] hostname =
+ hasCustomHost
+ ? new String[] {serviceInfo.getHostname(), LOCAL_TLD}
+ : deviceHostname;
+ final ArrayList<RecordInfo<?>> allRecords = new ArrayList<>(5);
- // Service PTR records
- ptrRecords = new ArrayList<>(serviceInfo.getSubtypes().size() + 1);
- ptrRecords.add(new RecordInfo<>(
- serviceInfo,
- new MdnsPointerRecord(
- serviceType,
- 0L /* receiptTimeMillis */,
- false /* cacheFlush */,
- NON_NAME_RECORDS_TTL_MILLIS,
- serviceName),
- true /* sharedName */));
- for (String subtype : serviceInfo.getSubtypes()) {
+ if (hasService) {
+ final String[] serviceType = splitServiceType(serviceInfo);
+ final String[] serviceName = splitFullyQualifiedName(serviceInfo, serviceType);
+ // Service PTR records
+ ptrRecords = new ArrayList<>(serviceInfo.getSubtypes().size() + 1);
ptrRecords.add(new RecordInfo<>(
- serviceInfo,
- new MdnsPointerRecord(
- MdnsUtils.constructFullSubtype(serviceType, subtype),
- 0L /* receiptTimeMillis */,
- false /* cacheFlush */,
- NON_NAME_RECORDS_TTL_MILLIS,
- serviceName),
- true /* sharedName */));
+ serviceInfo,
+ new MdnsPointerRecord(
+ serviceType,
+ 0L /* receiptTimeMillis */,
+ false /* cacheFlush */,
+ NON_NAME_RECORDS_TTL_MILLIS,
+ serviceName),
+ true /* sharedName */));
+ for (String subtype : serviceInfo.getSubtypes()) {
+ ptrRecords.add(new RecordInfo<>(
+ serviceInfo,
+ new MdnsPointerRecord(
+ MdnsUtils.constructFullSubtype(serviceType, subtype),
+ 0L /* receiptTimeMillis */,
+ false /* cacheFlush */,
+ NON_NAME_RECORDS_TTL_MILLIS,
+ serviceName),
+ true /* sharedName */));
+ }
+
+ srvRecord = new RecordInfo<>(
+ serviceInfo,
+ new MdnsServiceRecord(serviceName,
+ 0L /* receiptTimeMillis */,
+ true /* cacheFlush */,
+ NAME_RECORDS_TTL_MILLIS,
+ 0 /* servicePriority */, 0 /* serviceWeight */,
+ serviceInfo.getPort(),
+ hostname),
+ false /* sharedName */);
+
+ txtRecord = new RecordInfo<>(
+ serviceInfo,
+ new MdnsTextRecord(serviceName,
+ 0L /* receiptTimeMillis */,
+ // Service name is verified unique after probing
+ true /* cacheFlush */,
+ NON_NAME_RECORDS_TTL_MILLIS,
+ attrsToTextEntries(serviceInfo.getAttributes())),
+ false /* sharedName */);
+
+ allRecords.addAll(ptrRecords);
+ allRecords.add(srvRecord);
+ allRecords.add(txtRecord);
+ // Service type enumeration record (RFC6763 9.)
+ allRecords.add(new RecordInfo<>(
+ serviceInfo,
+ new MdnsPointerRecord(
+ DNS_SD_SERVICE_TYPE,
+ 0L /* receiptTimeMillis */,
+ false /* cacheFlush */,
+ NON_NAME_RECORDS_TTL_MILLIS,
+ serviceType),
+ true /* sharedName */));
+ } else {
+ ptrRecords = Collections.emptyList();
+ srvRecord = null;
+ txtRecord = null;
}
- srvRecord = new RecordInfo<>(
- serviceInfo,
- new MdnsServiceRecord(serviceName,
- 0L /* receiptTimeMillis */,
- true /* cacheFlush */,
- NAME_RECORDS_TTL_MILLIS, 0 /* servicePriority */, 0 /* serviceWeight */,
- serviceInfo.getPort(),
- deviceHostname),
- false /* sharedName */);
-
- txtRecord = new RecordInfo<>(
- serviceInfo,
- new MdnsTextRecord(serviceName,
- 0L /* receiptTimeMillis */,
- true /* cacheFlush */, // Service name is verified unique after probing
- NON_NAME_RECORDS_TTL_MILLIS,
- attrsToTextEntries(serviceInfo.getAttributes())),
- false /* sharedName */);
-
- final ArrayList<RecordInfo<?>> allRecords = new ArrayList<>(5);
- allRecords.addAll(ptrRecords);
- allRecords.add(srvRecord);
- allRecords.add(txtRecord);
- // Service type enumeration record (RFC6763 9.)
- allRecords.add(new RecordInfo<>(
- serviceInfo,
- new MdnsPointerRecord(
- DNS_SD_SERVICE_TYPE,
- 0L /* receiptTimeMillis */,
- false /* cacheFlush */,
- NON_NAME_RECORDS_TTL_MILLIS,
- serviceType),
- true /* sharedName */));
+ if (hasCustomHost) {
+ addressRecords = new ArrayList<>(serviceInfo.getHostAddresses().size());
+ for (InetAddress address : serviceInfo.getHostAddresses()) {
+ addressRecords.add(new RecordInfo<>(
+ serviceInfo,
+ new MdnsInetAddressRecord(hostname,
+ 0L /* receiptTimeMillis */,
+ true /* cacheFlush */,
+ NAME_RECORDS_TTL_MILLIS,
+ address),
+ false /* sharedName */));
+ }
+ allRecords.addAll(addressRecords);
+ } else {
+ addressRecords = Collections.emptyList();
+ }
this.allRecords = Collections.unmodifiableList(allRecords);
this.repliedServiceCount = repliedServiceCount;
@@ -368,32 +407,38 @@
/**
* @return The ID of the service identified by its name, or -1 if none.
*/
- private int getServiceByName(@NonNull String serviceName) {
+ private int getServiceByName(@Nullable String serviceName) {
+ if (TextUtils.isEmpty(serviceName)) {
+ return -1;
+ }
for (int i = 0; i < mServices.size(); i++) {
final ServiceRegistration registration = mServices.valueAt(i);
- if (MdnsUtils.equalsIgnoreDnsCase(serviceName,
- registration.serviceInfo.getServiceName())) {
+ if (MdnsUtils.equalsIgnoreDnsCase(
+ serviceName, registration.serviceInfo.getServiceName())) {
return mServices.keyAt(i);
}
}
return -1;
}
- private MdnsProber.ProbingInfo makeProbingInfo(int serviceId,
- @NonNull MdnsServiceRecord srvRecord,
- @NonNull List<MdnsInetAddressRecord> inetAddressRecords) {
+ private MdnsProber.ProbingInfo makeProbingInfo(
+ int serviceId, ServiceRegistration registration) {
final List<MdnsRecord> probingRecords = new ArrayList<>();
// Probe with cacheFlush cleared; it is set when announcing, as it was verified unique:
// RFC6762 10.2
- probingRecords.add(new MdnsServiceRecord(srvRecord.getName(),
- 0L /* receiptTimeMillis */,
- false /* cacheFlush */,
- srvRecord.getTtl(),
- srvRecord.getServicePriority(), srvRecord.getServiceWeight(),
- srvRecord.getServicePort(),
- srvRecord.getServiceHost()));
+ if (registration.srvRecord != null) {
+ MdnsServiceRecord srvRecord = registration.srvRecord.record;
+ probingRecords.add(new MdnsServiceRecord(srvRecord.getName(),
+ 0L /* receiptTimeMillis */,
+ false /* cacheFlush */,
+ srvRecord.getTtl(),
+ srvRecord.getServicePriority(), srvRecord.getServiceWeight(),
+ srvRecord.getServicePort(),
+ srvRecord.getServiceHost()));
+ }
- for (MdnsInetAddressRecord inetAddressRecord : inetAddressRecords) {
+ for (MdnsInetAddressRecord inetAddressRecord :
+ makeProbingInetAddressRecords(registration.serviceInfo)) {
probingRecords.add(new MdnsInetAddressRecord(inetAddressRecord.getName(),
0L /* receiptTimeMillis */,
false /* cacheFlush */,
@@ -510,6 +555,9 @@
public MdnsReplyInfo getReply(MdnsPacket packet, InetSocketAddress src) {
final long now = SystemClock.elapsedRealtime();
+ // TODO: b/322142420 - Set<RecordInfo<?>> may contain duplicate records wrapped in different
+ // RecordInfo<?>s when custom host is enabled.
+
// Use LinkedHashSet for preserving the insert order of the RRs, so that RRs of the same
// service or host are grouped together (which is more developer-friendly).
final Set<RecordInfo<?>> answerInfo = new LinkedHashSet<>();
@@ -520,8 +568,10 @@
for (MdnsRecord question : packet.questions) {
// Add answers from general records
if (addReplyFromService(question, mGeneralRecords, null /* servicePtrRecord */,
- null /* serviceSrvRecord */, null /* serviceTxtRecord */, replyUnicastEnabled,
- now, answerInfo, additionalAnswerInfo, Collections.emptyList())) {
+ null /* serviceSrvRecord */, null /* serviceTxtRecord */,
+ null /* hostname */,
+ replyUnicastEnabled, now, answerInfo, additionalAnswerInfo,
+ Collections.emptyList())) {
replyUnicast &= question.isUnicastReplyRequested();
}
@@ -530,7 +580,9 @@
final ServiceRegistration registration = mServices.valueAt(i);
if (registration.exiting || registration.isProbing) continue;
if (addReplyFromService(question, registration.allRecords, registration.ptrRecords,
- registration.srvRecord, registration.txtRecord, replyUnicastEnabled, now,
+ registration.srvRecord, registration.txtRecord,
+ registration.serviceInfo.getHostname(),
+ replyUnicastEnabled, now,
answerInfo, additionalAnswerInfo, packet.answers)) {
replyUnicast &= question.isUnicastReplyRequested();
registration.repliedServiceCount++;
@@ -548,7 +600,12 @@
final List<MdnsRecord> additionalAnswerRecords =
new ArrayList<>(additionalAnswerInfo.size());
for (RecordInfo<?> info : additionalAnswerInfo) {
- additionalAnswerRecords.add(info.record);
+ // Different RecordInfos may contain the same record.
+ // For example, when there are multiple services referring to the same custom host,
+ // there are multiple RecordInfos containing the same address record.
+ if (!additionalAnswerRecords.contains(info.record)) {
+ additionalAnswerRecords.add(info.record);
+ }
}
// RFC6762 6.1: negative responses
@@ -618,7 +675,10 @@
if (!replyUnicast) {
info.lastAdvertisedTimeMs = info.lastSentTimeMs;
}
- answerRecords.add(info.record);
+ // Different RecordInfos may the contain the same record
+ if (!answerRecords.contains(info.record)) {
+ answerRecords.add(info.record);
+ }
}
return new MdnsReplyInfo(answerRecords, additionalAnswerRecords, delayMs, dest, src,
@@ -642,6 +702,7 @@
@Nullable List<RecordInfo<MdnsPointerRecord>> servicePtrRecords,
@Nullable RecordInfo<MdnsServiceRecord> serviceSrvRecord,
@Nullable RecordInfo<MdnsTextRecord> serviceTxtRecord,
+ @Nullable String hostname,
boolean replyUnicastEnabled, long now, @NonNull Set<RecordInfo<?>> answerInfo,
@NonNull Set<RecordInfo<?>> additionalAnswerInfo,
@NonNull List<MdnsRecord> knownAnswerRecords) {
@@ -735,11 +796,7 @@
// RFC6763 12.1&.2: if including PTR or SRV record, include the address records it names
if (hasDnsSdPtrRecordAnswer || hasDnsSdSrvRecordAnswer) {
- for (RecordInfo<?> record : mGeneralRecords) {
- if (record.record instanceof MdnsInetAddressRecord) {
- additionalAnswerInfo.add(record);
- }
- }
+ additionalAnswerInfo.addAll(getInetAddressRecordsForHostname(hostname));
}
return true;
}
@@ -853,29 +910,46 @@
MdnsProber.ProbingInfo probeSuccessInfo)
throws IOException {
- final ServiceRegistration registration = mServices.get(probeSuccessInfo.getServiceId());
- if (registration == null) throw new IOException(
- "Service is not registered: " + probeSuccessInfo.getServiceId());
+ int serviceId = probeSuccessInfo.getServiceId();
+ final ServiceRegistration registration = mServices.get(serviceId);
+ if (registration == null) {
+ throw new IOException("Service is not registered: " + serviceId);
+ }
registration.setProbing(false);
- final ArrayList<MdnsRecord> answers = new ArrayList<>();
+ final Set<MdnsRecord> answersSet = new LinkedHashSet<>();
final ArrayList<MdnsRecord> additionalAnswers = new ArrayList<>();
- // Interface address records in general records
- for (RecordInfo<?> record : mGeneralRecords) {
- answers.add(record.record);
+ // When using default host, add interface address records from general records
+ if (TextUtils.isEmpty(registration.serviceInfo.getHostname())) {
+ for (RecordInfo<?> record : mGeneralRecords) {
+ answersSet.add(record.record);
+ }
+ } else {
+ // TODO: b/321617573 - include PTR records for addresses
+ // The custom host may have more addresses in other registrations
+ forEachActiveServiceRegistrationWithHostname(
+ registration.serviceInfo.getHostname(),
+ (id, otherRegistration) -> {
+ if (otherRegistration.isProbing) {
+ return;
+ }
+ for (RecordInfo<?> addressRecordInfo : otherRegistration.addressRecords) {
+ answersSet.add(addressRecordInfo.record);
+ }
+ });
}
// All service records
for (RecordInfo<?> info : registration.allRecords) {
- answers.add(info.record);
+ answersSet.add(info.record);
}
addNsecRecordsForUniqueNames(additionalAnswers,
mGeneralRecords.iterator(), registration.allRecords.iterator());
- return new MdnsAnnouncer.AnnouncementInfo(probeSuccessInfo.getServiceId(),
- answers, additionalAnswers);
+ return new MdnsAnnouncer.AnnouncementInfo(
+ probeSuccessInfo.getServiceId(), new ArrayList<>(answersSet), additionalAnswers);
}
/**
@@ -894,8 +968,13 @@
for (RecordInfo<MdnsPointerRecord> ptrRecord : registration.ptrRecords) {
answers.add(ptrRecord.record);
}
- answers.add(registration.srvRecord.record);
- answers.add(registration.txtRecord.record);
+ if (registration.srvRecord != null) {
+ answers.add(registration.srvRecord.record);
+ }
+ if (registration.txtRecord != null) {
+ answers.add(registration.txtRecord.record);
+ }
+ // TODO: Support custom host. It currently only supports default host.
for (RecordInfo<?> record : mGeneralRecords) {
if (record.record instanceof MdnsInetAddressRecord) {
answers.add(record.record);
@@ -910,70 +989,181 @@
Collections.emptyList() /* additionalRecords */);
}
+ /** Check if the record is in any service registration */
+ private boolean hasInetAddressRecord(@NonNull MdnsInetAddressRecord record) {
+ for (int i = 0; i < mServices.size(); i++) {
+ final ServiceRegistration registration = mServices.valueAt(i);
+ if (registration.exiting) continue;
+
+ for (RecordInfo<MdnsInetAddressRecord> localRecord : registration.addressRecords) {
+ if (Objects.equals(localRecord.record, record)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
/**
* Get the service IDs of services conflicting with a received packet.
+ *
+ * <p>It returns a Map of service ID => conflict type. Conflict type is a bitmap telling which
+ * part of the service is conflicting. See {@link MdnsInterfaceAdvertiser#CONFLICT_SERVICE} and
+ * {@link MdnsInterfaceAdvertiser#CONFLICT_HOST}.
*/
- public Set<Integer> getConflictingServices(MdnsPacket packet) {
+ public Map<Integer, Integer> getConflictingServices(MdnsPacket packet) {
// Avoid allocating a new set for each incoming packet: use an empty set by default.
- Set<Integer> conflicting = Collections.emptySet();
+ Map<Integer, Integer> conflicting = Collections.emptyMap();
for (MdnsRecord record : packet.answers) {
for (int i = 0; i < mServices.size(); i++) {
final ServiceRegistration registration = mServices.valueAt(i);
if (registration.exiting) continue;
- // Only look for conflicts in service name, as a different service name can be used
- // if there is a conflict, but there is nothing actionable if any other conflict
- // happens. In fact probing is only done for the service name in the SRV record.
- // This means only SRV and TXT records need to be checked.
- final RecordInfo<MdnsServiceRecord> srvRecord = registration.srvRecord;
- if (!MdnsUtils.equalsDnsLabelIgnoreDnsCase(record.getName(),
- srvRecord.record.getName())) {
- continue;
+ int conflictType = 0;
+
+ if (conflictForService(record, registration)) {
+ conflictType |= CONFLICT_SERVICE;
}
- // As per RFC6762 9., it's fine if the "conflict" is an identical record with same
- // data.
- if (record instanceof MdnsServiceRecord) {
- final MdnsServiceRecord local = srvRecord.record;
- final MdnsServiceRecord other = (MdnsServiceRecord) record;
- // Note "equals" does not consider TTL or receipt time, as intended here
- if (Objects.equals(local, other)) {
- continue;
+ if (conflictForHost(record, registration)) {
+ conflictType |= CONFLICT_HOST;
+ }
+
+ if (conflictType != 0) {
+ if (conflicting.isEmpty()) {
+ // Conflict was found: use a mutable set
+ conflicting = new ArrayMap<>();
}
+ final int serviceId = mServices.keyAt(i);
+ conflicting.put(serviceId, conflictType);
}
-
- if (record instanceof MdnsTextRecord) {
- final MdnsTextRecord local = registration.txtRecord.record;
- final MdnsTextRecord other = (MdnsTextRecord) record;
- if (Objects.equals(local, other)) {
- continue;
- }
- }
-
- if (conflicting.size() == 0) {
- // Conflict was found: use a mutable set
- conflicting = new ArraySet<>();
- }
- final int serviceId = mServices.keyAt(i);
- conflicting.add(serviceId);
}
}
return conflicting;
}
- private List<MdnsInetAddressRecord> makeProbingInetAddressRecords() {
- final List<MdnsInetAddressRecord> records = new ArrayList<>();
- if (mMdnsFeatureFlags.mIncludeInetAddressRecordsInProbing) {
- for (RecordInfo<?> record : mGeneralRecords) {
- if (record.record instanceof MdnsInetAddressRecord) {
- records.add((MdnsInetAddressRecord) record.record);
- }
+
+ private static boolean conflictForService(
+ @NonNull MdnsRecord record, @NonNull ServiceRegistration registration) {
+ if (registration.srvRecord == null) {
+ return false;
+ }
+
+ final RecordInfo<MdnsServiceRecord> srvRecord = registration.srvRecord;
+ if (!MdnsUtils.equalsDnsLabelIgnoreDnsCase(record.getName(), srvRecord.record.getName())) {
+ return false;
+ }
+
+ // As per RFC6762 9., it's fine if the "conflict" is an identical record with same
+ // data.
+ if (record instanceof MdnsServiceRecord) {
+ final MdnsServiceRecord local = srvRecord.record;
+ final MdnsServiceRecord other = (MdnsServiceRecord) record;
+ // Note "equals" does not consider TTL or receipt time, as intended here
+ if (Objects.equals(local, other)) {
+ return false;
}
}
+
+ if (record instanceof MdnsTextRecord) {
+ final MdnsTextRecord local = registration.txtRecord.record;
+ final MdnsTextRecord other = (MdnsTextRecord) record;
+ if (Objects.equals(local, other)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private boolean conflictForHost(
+ @NonNull MdnsRecord record, @NonNull ServiceRegistration registration) {
+ // Only custom hosts are checked. When using the default host, the hostname is derived from
+ // a UUID and it's supposed to be unique.
+ if (registration.serviceInfo.getHostname() == null) {
+ return false;
+ }
+
+ // The record's name cannot be registered by NsdManager so it's not a conflict.
+ if (record.getName().length != 2 || !record.getName()[1].equals(LOCAL_TLD)) {
+ return false;
+ }
+
+ // Different names. There won't be a conflict.
+ if (!MdnsUtils.equalsIgnoreDnsCase(
+ record.getName()[0], registration.serviceInfo.getHostname())) {
+ return false;
+ }
+
+ // If this registration has any address record and there's no identical record in the
+ // repository, it's a conflict. There will be no conflict if no registration has addresses
+ // for that hostname.
+ if (record instanceof MdnsInetAddressRecord) {
+ if (!registration.addressRecords.isEmpty()) {
+ return !hasInetAddressRecord((MdnsInetAddressRecord) record);
+ }
+ }
+
+ return false;
+ }
+
+ private List<RecordInfo<MdnsInetAddressRecord>> getInetAddressRecordsForHostname(
+ @Nullable String hostname) {
+ List<RecordInfo<MdnsInetAddressRecord>> records = new ArrayList<>();
+ if (TextUtils.isEmpty(hostname)) {
+ forEachAddressRecord(mGeneralRecords, records::add);
+ } else {
+ forEachActiveServiceRegistrationWithHostname(
+ hostname,
+ (id, service) -> {
+ if (service.isProbing) return;
+ records.addAll(service.addressRecords);
+ });
+ }
return records;
}
+ private List<MdnsInetAddressRecord> makeProbingInetAddressRecords(
+ @NonNull NsdServiceInfo serviceInfo) {
+ final List<MdnsInetAddressRecord> records = new ArrayList<>();
+ if (TextUtils.isEmpty(serviceInfo.getHostname())) {
+ if (mMdnsFeatureFlags.mIncludeInetAddressRecordsInProbing) {
+ forEachAddressRecord(mGeneralRecords, r -> records.add(r.record));
+ }
+ } else {
+ forEachActiveServiceRegistrationWithHostname(
+ serviceInfo.getHostname(),
+ (id, service) -> {
+ for (RecordInfo<MdnsInetAddressRecord> recordInfo :
+ service.addressRecords) {
+ records.add(recordInfo.record);
+ }
+ });
+ }
+ return records;
+ }
+
+ private static void forEachAddressRecord(
+ List<RecordInfo<?>> records, Consumer<RecordInfo<MdnsInetAddressRecord>> consumer) {
+ for (RecordInfo<?> record : records) {
+ if (record.record instanceof MdnsInetAddressRecord) {
+ consumer.accept((RecordInfo<MdnsInetAddressRecord>) record);
+ }
+ }
+ }
+
+ private void forEachActiveServiceRegistrationWithHostname(
+ @NonNull String hostname, BiConsumer<Integer, ServiceRegistration> consumer) {
+ for (int i = 0; i < mServices.size(); ++i) {
+ int id = mServices.keyAt(i);
+ ServiceRegistration service = mServices.valueAt(i);
+ if (service.exiting) continue;
+ if (MdnsUtils.equalsIgnoreDnsCase(service.serviceInfo.getHostname(), hostname)) {
+ consumer.accept(id, service);
+ }
+ }
+ }
+
/**
* (Re)set a service to the probing state.
* @return The {@link MdnsProber.ProbingInfo} to send for probing.
@@ -984,8 +1174,8 @@
if (registration == null) return null;
registration.setProbing(true);
- return makeProbingInfo(
- serviceId, registration.srvRecord.record, makeProbingInetAddressRecords());
+
+ return makeProbingInfo(serviceId, registration);
}
/**
@@ -1021,8 +1211,7 @@
final ServiceRegistration newService = new ServiceRegistration(mDeviceHostname, newInfo,
existing.repliedServiceCount, existing.sentPacketCount);
mServices.put(serviceId, newService);
- return makeProbingInfo(
- serviceId, newService.srvRecord.record, makeProbingInetAddressRecords());
+ return makeProbingInfo(serviceId, newService);
}
/**
diff --git a/service-t/src/com/android/server/connectivity/mdns/util/MdnsUtils.java b/service-t/src/com/android/server/connectivity/mdns/util/MdnsUtils.java
index 8fc8114..d553210 100644
--- a/service-t/src/com/android/server/connectivity/mdns/util/MdnsUtils.java
+++ b/service-t/src/com/android/server/connectivity/mdns/util/MdnsUtils.java
@@ -86,7 +86,10 @@
/**
* Compare two strings by DNS case-insensitive lowercase.
*/
- public static boolean equalsIgnoreDnsCase(@NonNull String a, @NonNull String b) {
+ public static boolean equalsIgnoreDnsCase(@Nullable String a, @Nullable String b) {
+ if (a == null || b == null) {
+ return a == null && b == null;
+ }
if (a.length() != b.length()) return false;
for (int i = 0; i < a.length(); i++) {
if (toDnsLowerCase(a.charAt(i)) != toDnsLowerCase(b.charAt(i))) {