blob: 6c25d76d0be6847df6c232faba4d41347e44aade [file] [log] [blame]
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001/*
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002 * Copyright (C) 2021 The Android Open Source Project
Irfan Sheriff77ec5582012-03-22 17:01:39 -07003 *
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
17package com.android.server;
18
Yuyang Huangd5896e72023-11-28 13:23:59 +090019import static android.Manifest.permission.DEVICE_POWER;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090020import static android.Manifest.permission.NETWORK_SETTINGS;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090021import static android.Manifest.permission.NETWORK_STACK;
paulhu2b9ed952022-02-10 21:58:32 +080022import static android.net.ConnectivityManager.NETID_UNSET;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090023import static android.net.NetworkCapabilities.TRANSPORT_VPN;
24import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090025import static android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK;
Paul Hu019621e2023-01-13 23:26:49 +080026import static android.net.nsd.NsdManager.MDNS_DISCOVERY_MANAGER_EVENT;
paulhu2b9ed952022-02-10 21:58:32 +080027import static android.net.nsd.NsdManager.MDNS_SERVICE_EVENT;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +090028import static android.net.nsd.NsdManager.RESOLVE_SERVICE_SUCCEEDED;
Yuyang Huang86d083f2023-12-12 19:56:41 +090029import static android.net.nsd.NsdManager.TYPE_REGEX;
30import static android.net.nsd.NsdManager.TYPE_SUBTYPE_LABEL_REGEX;
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +090031import static android.provider.DeviceConfig.NAMESPACE_TETHERING;
Motomu Utsumied4e7ec2023-09-13 14:58:32 +090032
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090033import static com.android.modules.utils.build.SdkLevel.isAtLeastU;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090034import static com.android.networkstack.apishim.ConstantsShim.REGISTER_NSD_OFFLOAD_ENGINE;
Paul Hu043bcd42023-07-14 16:38:25 +080035import static com.android.server.connectivity.mdns.MdnsAdvertiser.AdvertiserMetrics;
36import static com.android.server.connectivity.mdns.MdnsConstants.NO_PACKET;
Yuyang Huangde802c82023-05-02 17:14:22 +090037import static com.android.server.connectivity.mdns.MdnsRecord.MAX_LABEL_LENGTH;
Paul Hucdef3532023-06-18 14:47:35 +000038import static com.android.server.connectivity.mdns.util.MdnsUtils.Clock;
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090039
Paul Hu23fa2022023-01-13 22:57:24 +080040import android.annotation.NonNull;
Paul Hu4bd98ef2023-01-12 13:42:07 +080041import android.annotation.Nullable;
Yuyang Huangfc831702023-08-21 17:48:48 +090042import android.annotation.RequiresApi;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090043import android.app.ActivityManager;
paulhua262cc12019-08-12 16:25:11 +080044import android.content.Context;
Irfan Sheriff75006652012-04-17 23:15:29 -070045import android.content.Intent;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090046import android.net.ConnectivityManager;
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +090047import android.net.INetd;
Paul Hu75069ed2023-01-14 00:31:09 +080048import android.net.InetAddresses;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090049import android.net.LinkProperties;
50import android.net.Network;
paulhu2b9ed952022-02-10 21:58:32 +080051import android.net.mdns.aidl.DiscoveryInfo;
52import android.net.mdns.aidl.GetAddressInfo;
53import android.net.mdns.aidl.IMDnsEventListener;
54import android.net.mdns.aidl.RegistrationInfo;
55import android.net.mdns.aidl.ResolutionInfo;
Yuyang Huang86d083f2023-12-12 19:56:41 +090056import android.net.nsd.AdvertisingRequest;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070057import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090058import android.net.nsd.INsdManagerCallback;
59import android.net.nsd.INsdServiceConnector;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090060import android.net.nsd.IOffloadEngine;
paulhu2b9ed952022-02-10 21:58:32 +080061import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070062import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080063import android.net.nsd.NsdServiceInfo;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090064import android.net.nsd.OffloadEngine;
65import android.net.nsd.OffloadServiceInfo;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090066import android.net.wifi.WifiManager;
Paul Hub2e67d32023-04-18 05:50:14 +000067import android.os.Binder;
Yuyang Huangfc831702023-08-21 17:48:48 +090068import android.os.Build;
Hugo Benichi803a2f02017-04-24 11:35:06 +090069import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080070import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090071import android.os.IBinder;
Paul Hu4bd98ef2023-01-12 13:42:07 +080072import android.os.Looper;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070073import android.os.Message;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090074import android.os.RemoteCallbackList;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090075import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070076import android.os.UserHandle;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090077import android.provider.DeviceConfig;
Paul Hu23fa2022023-01-13 22:57:24 +080078import android.text.TextUtils;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090079import android.util.ArraySet;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090080import android.util.Log;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +090081import android.util.Pair;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070082import android.util.SparseArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070083
paulhua262cc12019-08-12 16:25:11 +080084import com.android.internal.annotations.VisibleForTesting;
Paul Hub2e67d32023-04-18 05:50:14 +000085import com.android.internal.util.IndentingPrintWriter;
paulhua262cc12019-08-12 16:25:11 +080086import com.android.internal.util.State;
87import com.android.internal.util.StateMachine;
Paul Hucdef3532023-06-18 14:47:35 +000088import com.android.metrics.NetworkNsdReportedMetrics;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090089import com.android.modules.utils.build.SdkLevel;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090090import com.android.net.module.util.CollectionUtils;
Paul Hu4bd98ef2023-01-12 13:42:07 +080091import com.android.net.module.util.DeviceConfigUtils;
Yuyang Huanga6a6ff92023-04-24 13:33:34 +090092import com.android.net.module.util.InetAddressUtils;
paulhu3ffffe72021-09-16 10:15:22 +080093import com.android.net.module.util.PermissionUtils;
Paul Hub2e67d32023-04-18 05:50:14 +000094import com.android.net.module.util.SharedLog;
Paul Hu4bd98ef2023-01-12 13:42:07 +080095import com.android.server.connectivity.mdns.ExecutorProvider;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090096import com.android.server.connectivity.mdns.MdnsAdvertiser;
Yuyang Huange5cba9c2023-11-02 18:05:47 +090097import com.android.server.connectivity.mdns.MdnsAdvertisingOptions;
Paul Hu4bd98ef2023-01-12 13:42:07 +080098import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
Yuyang Huangb96a0712023-09-07 15:13:15 +090099import com.android.server.connectivity.mdns.MdnsFeatureFlags;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900100import com.android.server.connectivity.mdns.MdnsInterfaceSocket;
Paul Hu4bd98ef2023-01-12 13:42:07 +0800101import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
Paul Hu23fa2022023-01-13 22:57:24 +0800102import com.android.server.connectivity.mdns.MdnsSearchOptions;
103import com.android.server.connectivity.mdns.MdnsServiceBrowserListener;
104import com.android.server.connectivity.mdns.MdnsServiceInfo;
Paul Hu4bd98ef2023-01-12 13:42:07 +0800105import com.android.server.connectivity.mdns.MdnsSocketProvider;
Yuyang Huangde802c82023-05-02 17:14:22 +0900106import com.android.server.connectivity.mdns.util.MdnsUtils;
paulhua262cc12019-08-12 16:25:11 +0800107
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700108import java.io.FileDescriptor;
109import java.io.PrintWriter;
Yuyang Huangaa0e9602023-03-17 12:43:09 +0900110import java.net.Inet6Address;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700111import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900112import java.net.NetworkInterface;
113import java.net.SocketException;
114import java.net.UnknownHostException;
Paul Hu2b865912023-03-06 14:27:53 +0800115import java.util.ArrayList;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900116import java.util.Arrays;
Kangping Dong5af24b62023-12-10 21:41:16 +0800117import java.util.Collection;
Yuyang Huang170d42f2023-12-09 15:26:16 +0900118import java.util.Collections;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700119import java.util.HashMap;
Kangping Dong5af24b62023-12-10 21:41:16 +0800120import java.util.LinkedHashMap;
Paul Hu23fa2022023-01-13 22:57:24 +0800121import java.util.List;
Paul Hu75069ed2023-01-14 00:31:09 +0800122import java.util.Map;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900123import java.util.Objects;
Paul Hu812e9212023-06-20 06:24:53 +0000124import java.util.Set;
Paul Hu23fa2022023-01-13 22:57:24 +0800125import java.util.regex.Matcher;
126import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700127
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700128/**
129 * Network Service Discovery Service handles remote service discovery operation requests by
130 * implementing the INsdManager interface.
131 *
132 * @hide
133 */
Yuyang Huangfc831702023-08-21 17:48:48 +0900134@RequiresApi(Build.VERSION_CODES.TIRAMISU)
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700135public class NsdService extends INsdManager.Stub {
136 private static final String TAG = "NsdService";
137 private static final String MDNS_TAG = "mDnsConnector";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900138 /**
139 * Enable discovery using the Java DiscoveryManager, instead of the legacy mdnsresponder
140 * implementation.
141 */
Paul Hu4bd98ef2023-01-12 13:42:07 +0800142 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +0800143 private static final String LOCAL_DOMAIN_NAME = "local";
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700144
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900145 /**
146 * Enable advertising using the Java MdnsAdvertiser, instead of the legacy mdnsresponder
147 * implementation.
148 */
149 private static final String MDNS_ADVERTISER_VERSION = "mdns_advertiser_version";
150
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900151 /**
152 * Comma-separated list of type:flag mappings indicating the flags to use to allowlist
153 * discovery/advertising using MdnsDiscoveryManager / MdnsAdvertiser for a given type.
154 *
155 * For example _mytype._tcp.local and _othertype._tcp.local would be configured with:
156 * _mytype._tcp:mytype,_othertype._tcp.local:othertype
157 *
158 * In which case the flags:
159 * "mdns_discovery_manager_allowlist_mytype_version",
160 * "mdns_advertiser_allowlist_mytype_version",
161 * "mdns_discovery_manager_allowlist_othertype_version",
162 * "mdns_advertiser_allowlist_othertype_version"
163 * would be used to toggle MdnsDiscoveryManager / MdnsAdvertiser for each type. The flags will
164 * be read with
Motomu Utsumi624aeb42023-08-15 15:52:27 +0900165 * {@link DeviceConfigUtils#isTetheringFeatureEnabled}
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900166 *
167 * @see #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX
168 * @see #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX
169 * @see #MDNS_ALLOWLIST_FLAG_SUFFIX
170 */
171 private static final String MDNS_TYPE_ALLOWLIST_FLAGS = "mdns_type_allowlist_flags";
172
173 private static final String MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX =
174 "mdns_discovery_manager_allowlist_";
175 private static final String MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX =
176 "mdns_advertiser_allowlist_";
177 private static final String MDNS_ALLOWLIST_FLAG_SUFFIX = "_version";
178
Yuyang Huang86d083f2023-12-12 19:56:41 +0900179
Kangping Dong5af24b62023-12-10 21:41:16 +0800180
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900181 @VisibleForTesting
182 static final String MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
183 "mdns_config_running_app_active_importance_cutoff";
184 @VisibleForTesting
185 static final int DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
186 ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
187 private final int mRunningAppActiveImportanceCutoff;
188
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900189 public static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +0000190 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900191 private static final int IFACE_IDX_ANY = 0;
Paul Hu812e9212023-06-20 06:24:53 +0000192 private static final int MAX_SERVICES_COUNT_METRIC_PER_CLIENT = 100;
193 @VisibleForTesting
194 static final int NO_TRANSACTION = -1;
Paul Hubad6fe92023-07-24 21:25:22 +0800195 private static final int NO_SENT_QUERY_COUNT = 0;
196 private static final int DISCOVERY_QUERY_SENT_CALLBACK = 1000;
Kangping Dong5af24b62023-12-10 21:41:16 +0800197 private static final int MAX_SUBTYPE_COUNT = 100;
Paul Hu14667de2023-04-17 22:42:47 +0800198 private static final SharedLog LOGGER = new SharedLog("serviceDiscovery");
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700199
Hugo Benichi32be63d2017-04-05 14:06:11 +0900200 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900201 private final NsdStateMachine mNsdStateMachine;
Ken Chen80c9f6f2023-11-15 18:24:54 +0800202 // It can be null on V+ device since mdns native service provided by netd is removed.
203 private final @Nullable MDnsManager mMDnsManager;
paulhu2b9ed952022-02-10 21:58:32 +0800204 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900205 @NonNull
206 private final Dependencies mDeps;
207 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800208 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900209 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800210 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900211 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800212 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900213 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900214 private final MdnsAdvertiser mAdvertiser;
Paul Hu777ed052023-06-19 13:35:15 +0000215 @NonNull
216 private final Clock mClock;
Paul Hu14667de2023-04-17 22:42:47 +0800217 private final SharedLog mServiceLogs = LOGGER.forSubComponent(TAG);
Paul Hu23fa2022023-01-13 22:57:24 +0800218 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800219 // state machine thread. If change this outside state machine, it will need to introduce
220 // synchronization.
221 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800222 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700223
224 /**
225 * Clients receiving asynchronous messages
226 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900227 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700228
Paul Hud44e1b72023-06-16 02:07:42 +0000229 /* A map from transaction(unique) id to client info */
230 private final SparseArray<ClientInfo> mTransactionIdToClientInfoMap = new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700231
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900232 // Note this is not final to avoid depending on the Wi-Fi service starting before NsdService
233 @Nullable
234 private WifiManager.MulticastLock mHeldMulticastLock;
235 // Fulfilled network requests that require the Wi-Fi lock: key is the obtained Network
236 // (non-null), value is the requested Network (nullable)
237 @NonNull
238 private final ArraySet<Network> mWifiLockRequiredNetworks = new ArraySet<>();
239 @NonNull
240 private final ArraySet<Integer> mRunningAppActiveUids = new ArraySet<>();
241
Luke Huang05298582021-06-13 16:52:05 +0000242 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700243
Hugo Benichi32be63d2017-04-05 14:06:11 +0900244 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700245 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800246 // The count of the connected legacy clients.
247 private int mLegacyClientCount = 0;
Paul Hub2e67d32023-04-18 05:50:14 +0000248 // The number of client that ever connected.
249 private int mClientNumberId = 1;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700250
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900251 private final RemoteCallbackList<IOffloadEngine> mOffloadEngines =
252 new RemoteCallbackList<>();
253
254 private static class OffloadEngineInfo {
255 @NonNull final String mInterfaceName;
256 final long mOffloadCapabilities;
257 final long mOffloadType;
258 @NonNull final IOffloadEngine mOffloadEngine;
259
260 OffloadEngineInfo(@NonNull IOffloadEngine offloadEngine,
261 @NonNull String interfaceName, long capabilities, long offloadType) {
262 this.mOffloadEngine = offloadEngine;
263 this.mInterfaceName = interfaceName;
264 this.mOffloadCapabilities = capabilities;
265 this.mOffloadType = offloadType;
266 }
267 }
268
Paul Hu812e9212023-06-20 06:24:53 +0000269 @VisibleForTesting
270 static class MdnsListener implements MdnsServiceBrowserListener {
Paul Hud44e1b72023-06-16 02:07:42 +0000271 protected final int mClientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800272 protected final int mTransactionId;
273 @NonNull
Paul Hu23fa2022023-01-13 22:57:24 +0800274 protected final String mListenedServiceType;
275
Kangping Dong97b2adc2024-01-11 16:00:37 +0800276 MdnsListener(int clientRequestId, int transactionId, @NonNull String listenedServiceType) {
Paul Hud44e1b72023-06-16 02:07:42 +0000277 mClientRequestId = clientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800278 mTransactionId = transactionId;
Paul Hu23fa2022023-01-13 22:57:24 +0800279 mListenedServiceType = listenedServiceType;
280 }
281
282 @NonNull
283 public String getListenedServiceType() {
284 return mListenedServiceType;
285 }
286
287 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000288 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
289 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800290
291 @Override
292 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
293
294 @Override
295 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
296
297 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000298 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
299 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800300
301 @Override
302 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
303
304 @Override
305 public void onSearchStoppedWithError(int error) { }
306
307 @Override
308 public void onSearchFailedToStart() { }
309
310 @Override
Paul Hubad6fe92023-07-24 21:25:22 +0800311 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
312 int sentQueryTransactionId) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800313
314 @Override
315 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
316 }
317
318 private class DiscoveryListener extends MdnsListener {
319
Paul Hud44e1b72023-06-16 02:07:42 +0000320 DiscoveryListener(int clientRequestId, int transactionId,
Kangping Dong97b2adc2024-01-11 16:00:37 +0800321 @NonNull String listenServiceType) {
322 super(clientRequestId, transactionId, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800323 }
324
325 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000326 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
327 boolean isServiceFromCache) {
Paul Hu019621e2023-01-13 23:26:49 +0800328 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
329 NsdManager.SERVICE_FOUND,
Paul Hua6bc4632023-06-26 01:18:29 +0000330 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu23fa2022023-01-13 22:57:24 +0800331 }
332
333 @Override
334 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800335 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
336 NsdManager.SERVICE_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000337 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800338 }
Paul Hubad6fe92023-07-24 21:25:22 +0800339
340 @Override
341 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
342 int sentQueryTransactionId) {
343 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
344 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
345 }
Paul Hu23fa2022023-01-13 22:57:24 +0800346 }
347
Paul Hu75069ed2023-01-14 00:31:09 +0800348 private class ResolutionListener extends MdnsListener {
349
Paul Hud44e1b72023-06-16 02:07:42 +0000350 ResolutionListener(int clientRequestId, int transactionId,
Kangping Dong97b2adc2024-01-11 16:00:37 +0800351 @NonNull String listenServiceType) {
352 super(clientRequestId, transactionId, listenServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800353 }
354
355 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000356 public void onServiceFound(MdnsServiceInfo serviceInfo, boolean isServiceFromCache) {
Paul Hu75069ed2023-01-14 00:31:09 +0800357 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
358 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
Paul Hua6bc4632023-06-26 01:18:29 +0000359 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu75069ed2023-01-14 00:31:09 +0800360 }
Paul Hubad6fe92023-07-24 21:25:22 +0800361
362 @Override
363 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
364 int sentQueryTransactionId) {
365 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
366 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
367 }
Paul Hu75069ed2023-01-14 00:31:09 +0800368 }
369
Paul Hu30bd70d2023-02-07 13:20:56 +0000370 private class ServiceInfoListener extends MdnsListener {
371
Paul Hud44e1b72023-06-16 02:07:42 +0000372 ServiceInfoListener(int clientRequestId, int transactionId,
Kangping Dong97b2adc2024-01-11 16:00:37 +0800373 @NonNull String listenServiceType) {
374 super(clientRequestId, transactionId, listenServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +0000375 }
376
377 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000378 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
379 boolean isServiceFromCache) {
Paul Hu30bd70d2023-02-07 13:20:56 +0000380 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
381 NsdManager.SERVICE_UPDATED,
Paul Hua6bc4632023-06-26 01:18:29 +0000382 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu30bd70d2023-02-07 13:20:56 +0000383 }
384
385 @Override
386 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) {
387 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
388 NsdManager.SERVICE_UPDATED,
Paul Hud44e1b72023-06-16 02:07:42 +0000389 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000390 }
391
392 @Override
393 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) {
394 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
395 NsdManager.SERVICE_UPDATED_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000396 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000397 }
Paul Hubad6fe92023-07-24 21:25:22 +0800398
399 @Override
400 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
401 int sentQueryTransactionId) {
402 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
403 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
404 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000405 }
406
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900407 private class SocketRequestMonitor implements MdnsSocketProvider.SocketRequestMonitor {
408 @Override
409 public void onSocketRequestFulfilled(@Nullable Network socketNetwork,
410 @NonNull MdnsInterfaceSocket socket, @NonNull int[] transports) {
411 // The network may be null for Wi-Fi SoftAp interfaces (tethering), but there is no APF
412 // filtering on such interfaces, so taking the multicast lock is not necessary to
413 // disable APF filtering of multicast.
414 if (socketNetwork == null
415 || !CollectionUtils.contains(transports, TRANSPORT_WIFI)
416 || CollectionUtils.contains(transports, TRANSPORT_VPN)) {
417 return;
418 }
419
420 if (mWifiLockRequiredNetworks.add(socketNetwork)) {
421 updateMulticastLock();
422 }
423 }
424
425 @Override
426 public void onSocketDestroyed(@Nullable Network socketNetwork,
427 @NonNull MdnsInterfaceSocket socket) {
428 if (mWifiLockRequiredNetworks.remove(socketNetwork)) {
429 updateMulticastLock();
430 }
431 }
432 }
433
434 private class UidImportanceListener implements ActivityManager.OnUidImportanceListener {
435 private final Handler mHandler;
436
437 private UidImportanceListener(Handler handler) {
438 mHandler = handler;
439 }
440
441 @Override
442 public void onUidImportance(int uid, int importance) {
443 mHandler.post(() -> handleUidImportanceChanged(uid, importance));
444 }
445 }
446
447 private void handleUidImportanceChanged(int uid, int importance) {
448 // Lower importance values are more "important"
449 final boolean modified = importance <= mRunningAppActiveImportanceCutoff
450 ? mRunningAppActiveUids.add(uid)
451 : mRunningAppActiveUids.remove(uid);
452 if (modified) {
453 updateMulticastLock();
454 }
455 }
456
457 /**
458 * Take or release the lock based on updated internal state.
459 *
460 * This determines whether the lock needs to be held based on
461 * {@link #mWifiLockRequiredNetworks}, {@link #mRunningAppActiveUids} and
462 * {@link ClientInfo#mClientRequests}, so it must be called after any of the these have been
463 * updated.
464 */
465 private void updateMulticastLock() {
466 final int needsLockUid = getMulticastLockNeededUid();
467 if (needsLockUid >= 0 && mHeldMulticastLock == null) {
468 final WifiManager wm = mContext.getSystemService(WifiManager.class);
469 if (wm == null) {
470 Log.wtf(TAG, "Got a TRANSPORT_WIFI network without WifiManager");
471 return;
472 }
473 mHeldMulticastLock = wm.createMulticastLock(TAG);
474 mHeldMulticastLock.acquire();
475 mServiceLogs.log("Taking multicast lock for uid " + needsLockUid);
476 } else if (needsLockUid < 0 && mHeldMulticastLock != null) {
477 mHeldMulticastLock.release();
478 mHeldMulticastLock = null;
479 mServiceLogs.log("Released multicast lock");
480 }
481 }
482
483 /**
484 * @return The UID of an app requiring the multicast lock, or -1 if none.
485 */
486 private int getMulticastLockNeededUid() {
487 if (mWifiLockRequiredNetworks.size() == 0) {
488 // Return early if NSD is not active, or not on any relevant network
489 return -1;
490 }
Paul Hud44e1b72023-06-16 02:07:42 +0000491 for (int i = 0; i < mTransactionIdToClientInfoMap.size(); i++) {
492 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.valueAt(i);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900493 if (!mRunningAppActiveUids.contains(clientInfo.mUid)) {
494 // Ignore non-active UIDs
495 continue;
496 }
497
498 if (clientInfo.hasAnyJavaBackendRequestForNetworks(mWifiLockRequiredNetworks)) {
499 return clientInfo.mUid;
500 }
501 }
502 return -1;
503 }
504
Paul Hu019621e2023-01-13 23:26:49 +0800505 /**
506 * Data class of mdns service callback information.
507 */
508 private static class MdnsEvent {
Paul Hud44e1b72023-06-16 02:07:42 +0000509 final int mClientRequestId;
Paul Hubad6fe92023-07-24 21:25:22 +0800510 @Nullable
Paul Hu019621e2023-01-13 23:26:49 +0800511 final MdnsServiceInfo mMdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000512 final boolean mIsServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800513
Paul Hubad6fe92023-07-24 21:25:22 +0800514 MdnsEvent(int clientRequestId) {
515 this(clientRequestId, null /* mdnsServiceInfo */, false /* isServiceFromCache */);
516 }
517
518 MdnsEvent(int clientRequestId, @Nullable MdnsServiceInfo mdnsServiceInfo) {
Paul Hua6bc4632023-06-26 01:18:29 +0000519 this(clientRequestId, mdnsServiceInfo, false /* isServiceFromCache */);
520 }
521
Paul Hubad6fe92023-07-24 21:25:22 +0800522 MdnsEvent(int clientRequestId, @Nullable MdnsServiceInfo mdnsServiceInfo,
Paul Hua6bc4632023-06-26 01:18:29 +0000523 boolean isServiceFromCache) {
Paul Hud44e1b72023-06-16 02:07:42 +0000524 mClientRequestId = clientRequestId;
Paul Hu019621e2023-01-13 23:26:49 +0800525 mMdnsServiceInfo = mdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000526 mIsServiceFromCache = isServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800527 }
528 }
529
Paul Hu77c11182023-10-23 16:17:32 +0800530 // TODO: Use a Handler instead of a StateMachine since there are no state changes.
Irfan Sheriff75006652012-04-17 23:15:29 -0700531 private class NsdStateMachine extends StateMachine {
532
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700533 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700534
535 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700536 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900537 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700538 }
539
Luke Huang92860f92021-06-23 06:29:30 +0000540 private void maybeStartDaemon() {
Paul Hu4a87ed42024-01-10 08:58:30 +0000541 if (mIsDaemonStarted) {
542 if (DBG) Log.d(TAG, "Daemon is already started.");
Ken Chen80c9f6f2023-11-15 18:24:54 +0800543 return;
544 }
545
Paul Hu4a87ed42024-01-10 08:58:30 +0000546 if (mMDnsManager == null) {
547 Log.wtf(TAG, "maybeStartDaemon: mMDnsManager is null");
paulhu2b9ed952022-02-10 21:58:32 +0800548 return;
549 }
550 mMDnsManager.registerEventListener(mMDnsEventCallback);
551 mMDnsManager.startDaemon();
552 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000553 maybeScheduleStop();
Paul Hub2e67d32023-04-18 05:50:14 +0000554 mServiceLogs.log("Start mdns_responder daemon");
Luke Huang05298582021-06-13 16:52:05 +0000555 }
556
paulhu2b9ed952022-02-10 21:58:32 +0800557 private void maybeStopDaemon() {
Paul Hu4a87ed42024-01-10 08:58:30 +0000558 if (!mIsDaemonStarted) {
559 if (DBG) Log.d(TAG, "Daemon has not been started.");
Ken Chen80c9f6f2023-11-15 18:24:54 +0800560 return;
561 }
562
Paul Hu4a87ed42024-01-10 08:58:30 +0000563 if (mMDnsManager == null) {
564 Log.wtf(TAG, "maybeStopDaemon: mMDnsManager is null");
paulhu2b9ed952022-02-10 21:58:32 +0800565 return;
566 }
567 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
568 mMDnsManager.stopDaemon();
569 mIsDaemonStarted = false;
Paul Hub2e67d32023-04-18 05:50:14 +0000570 mServiceLogs.log("Stop mdns_responder daemon");
paulhu2b9ed952022-02-10 21:58:32 +0800571 }
572
Luke Huang92860f92021-06-23 06:29:30 +0000573 private boolean isAnyRequestActive() {
Paul Hud44e1b72023-06-16 02:07:42 +0000574 return mTransactionIdToClientInfoMap.size() != 0;
Luke Huang92860f92021-06-23 06:29:30 +0000575 }
576
577 private void scheduleStop() {
578 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
579 }
580 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800581 // The native daemon should stay alive and can't be cleanup
582 // if any legacy client connected.
583 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000584 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000585 }
586 }
587
Luke Huang92860f92021-06-23 06:29:30 +0000588 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000589 this.removeMessages(NsdManager.DAEMON_CLEANUP);
590 }
591
Paul Hu23fa2022023-01-13 22:57:24 +0800592 private void maybeStartMonitoringSockets() {
593 if (mIsMonitoringSocketsStarted) {
594 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
595 return;
596 }
597
598 mMdnsSocketProvider.startMonitoringSockets();
599 mIsMonitoringSocketsStarted = true;
600 }
601
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900602 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
603 if (!mIsMonitoringSocketsStarted) return;
604 if (isAnyRequestActive()) return;
605
Paul Hu58f20602023-02-18 11:41:07 +0800606 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800607 mIsMonitoringSocketsStarted = false;
608 }
609
Hugo Benichi803a2f02017-04-24 11:35:06 +0900610 NsdStateMachine(String name, Handler handler) {
611 super(name, handler);
Paul Hu77c11182023-10-23 16:17:32 +0800612 addState(mEnabledState);
paulhu5568f452021-11-30 13:31:29 +0800613 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900614 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700615 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700616 }
617
Irfan Sheriff75006652012-04-17 23:15:29 -0700618 class EnabledState extends State {
619 @Override
620 public void enter() {
621 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700622 }
623
624 @Override
625 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000626 // TODO: it is incorrect to stop the daemon without expunging all requests
627 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000628 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700629 }
630
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700631 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900632 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800633 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700634 return true;
635 }
636 return false;
637 }
638
Paul Hu508a0122023-09-11 15:31:33 +0800639 private ClientRequest storeLegacyRequestMap(int clientRequestId, int transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +0000640 ClientInfo clientInfo, int what, long startTimeMs) {
Paul Hu508a0122023-09-11 15:31:33 +0800641 final LegacyClientRequest request =
642 new LegacyClientRequest(transactionId, what, startTimeMs);
643 clientInfo.mClientRequests.put(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000644 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000645 // Remove the cleanup event because here comes a new request.
646 cancelStop();
Paul Hu508a0122023-09-11 15:31:33 +0800647 return request;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700648 }
649
Paul Hud44e1b72023-06-16 02:07:42 +0000650 private void storeAdvertiserRequestMap(int clientRequestId, int transactionId,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900651 ClientInfo clientInfo, @Nullable Network requestedNetwork) {
Paul Hu777ed052023-06-19 13:35:15 +0000652 clientInfo.mClientRequests.put(clientRequestId, new AdvertiserClientRequest(
Paul Hu812e9212023-06-20 06:24:53 +0000653 transactionId, requestedNetwork, mClock.elapsedRealtime()));
Paul Hud44e1b72023-06-16 02:07:42 +0000654 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900655 updateMulticastLock();
Paul Hu23fa2022023-01-13 22:57:24 +0800656 }
657
Paul Hud44e1b72023-06-16 02:07:42 +0000658 private void removeRequestMap(
659 int clientRequestId, int transactionId, ClientInfo clientInfo) {
660 final ClientRequest existing = clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900661 if (existing == null) return;
Paul Hud44e1b72023-06-16 02:07:42 +0000662 clientInfo.mClientRequests.remove(clientRequestId);
663 mTransactionIdToClientInfoMap.remove(transactionId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900664
665 if (existing instanceof LegacyClientRequest) {
666 maybeScheduleStop();
667 } else {
668 maybeStopMonitoringSocketsIfNoActiveRequest();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900669 updateMulticastLock();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900670 }
671 }
672
Paul Hu508a0122023-09-11 15:31:33 +0800673 private ClientRequest storeDiscoveryManagerRequestMap(int clientRequestId,
674 int transactionId, MdnsListener listener, ClientInfo clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900675 @Nullable Network requestedNetwork) {
Paul Hu508a0122023-09-11 15:31:33 +0800676 final DiscoveryManagerRequest request = new DiscoveryManagerRequest(transactionId,
677 listener, requestedNetwork, mClock.elapsedRealtime());
678 clientInfo.mClientRequests.put(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000679 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900680 updateMulticastLock();
Paul Hu508a0122023-09-11 15:31:33 +0800681 return request;
Paul Hu23fa2022023-01-13 22:57:24 +0800682 }
683
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900684 /**
685 * Truncate a service name to up to 63 UTF-8 bytes.
686 *
687 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
688 * names used in registerService follows historical behavior (see mdnsresponder
689 * handle_regservice_request).
690 */
691 @NonNull
692 private String truncateServiceName(@NonNull String originalName) {
Yuyang Huangde802c82023-05-02 17:14:22 +0900693 return MdnsUtils.truncateServiceName(originalName, MAX_LABEL_LENGTH);
Paul Hu23fa2022023-01-13 22:57:24 +0800694 }
695
Paul Hud44e1b72023-06-16 02:07:42 +0000696 private void stopDiscoveryManagerRequest(ClientRequest request, int clientRequestId,
697 int transactionId, ClientInfo clientInfo) {
Paul Hue4f5f252023-02-16 21:13:47 +0800698 clientInfo.unregisterMdnsListenerFromRequest(request);
Paul Hud44e1b72023-06-16 02:07:42 +0000699 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hue4f5f252023-02-16 21:13:47 +0800700 }
701
Paul Hu77c11182023-10-23 16:17:32 +0800702 private ClientInfo getClientInfoForReply(Message msg) {
703 final ListenerArgs args = (ListenerArgs) msg.obj;
704 return mClients.get(args.connector);
705 }
706
Kangping Dong5af24b62023-12-10 21:41:16 +0800707 /**
708 * Returns {@code false} if {@code subtypes} exceeds the maximum number limit or
709 * contains invalid subtype label.
710 */
711 private boolean checkSubtypeLabels(Set<String> subtypes) {
712 if (subtypes.size() > MAX_SUBTYPE_COUNT) {
713 mServiceLogs.e(
714 "Too many subtypes: " + subtypes.size() + " (max = "
715 + MAX_SUBTYPE_COUNT + ")");
716 return false;
717 }
718
719 for (String subtype : subtypes) {
720 if (!checkSubtypeLabel(subtype)) {
721 mServiceLogs.e("Subtype " + subtype + " is invalid");
722 return false;
723 }
724 }
725 return true;
726 }
727
728 private Set<String> dedupSubtypeLabels(Collection<String> subtypes) {
729 final Map<String, String> subtypeMap = new LinkedHashMap<>(subtypes.size());
730 for (String subtype : subtypes) {
731 subtypeMap.put(MdnsUtils.toDnsLowerCase(subtype), subtype);
732 }
733 return new ArraySet<>(subtypeMap.values());
734 }
735
Irfan Sheriff75006652012-04-17 23:15:29 -0700736 @Override
737 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900738 final ClientInfo clientInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000739 final int transactionId;
740 final int clientRequestId = msg.arg2;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900741 final OffloadEngineInfo offloadEngineInfo;
Irfan Sheriff75006652012-04-17 23:15:29 -0700742 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800743 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800744 if (DBG) Log.d(TAG, "Discover services");
Yuyang Huang86d083f2023-12-12 19:56:41 +0900745 final ListenerArgs args = (ListenerArgs) msg.obj;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900746 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000747 // If the binder death notification for a INsdManagerCallback was received
748 // before any calls are received by NsdService, the clientInfo would be
749 // cleared and cause NPE. Add a null check here to prevent this corner case.
750 if (clientInfo == null) {
751 Log.e(TAG, "Unknown connector in discovery");
752 break;
753 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700754
755 if (requestLimitReached(clientInfo)) {
Paul Hu508a0122023-09-11 15:31:33 +0800756 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
757 NsdManager.FAILURE_MAX_LIMIT, true /* isLegacy */);
Irfan Sheriff75006652012-04-17 23:15:29 -0700758 break;
759 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700760
Paul Hu23fa2022023-01-13 22:57:24 +0800761 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000762 transactionId = getUniqueId();
Yuyang Huang170d42f2023-12-09 15:26:16 +0900763 final Pair<String, List<String>> typeAndSubtype =
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900764 parseTypeAndSubtype(info.getServiceType());
765 final String serviceType = typeAndSubtype == null
766 ? null : typeAndSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800767 if (clientInfo.mUseJavaBackend
768 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900769 || useDiscoveryManagerForType(serviceType)) {
Yuyang Huang170d42f2023-12-09 15:26:16 +0900770 if (serviceType == null || typeAndSubtype.second.size() > 1) {
Paul Hu508a0122023-09-11 15:31:33 +0800771 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
772 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Paul Hu23fa2022023-01-13 22:57:24 +0800773 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700774 }
Paul Hu23fa2022023-01-13 22:57:24 +0800775
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900776 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800777 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +0000778 final MdnsListener listener = new DiscoveryListener(clientRequestId,
Kangping Dong97b2adc2024-01-11 16:00:37 +0800779 transactionId, listenServiceType);
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900780 final MdnsSearchOptions.Builder optionsBuilder =
781 MdnsSearchOptions.newBuilder()
782 .setNetwork(info.getNetwork())
Yuyang Huangff963222023-06-01 18:42:42 +0900783 .setRemoveExpiredService(true)
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900784 .setIsPassiveMode(true);
Yuyang Huang170d42f2023-12-09 15:26:16 +0900785 if (!typeAndSubtype.second.isEmpty()) {
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900786 // The parsing ensures subtype starts with an underscore.
787 // MdnsSearchOptions expects the underscore to not be present.
Yuyang Huang170d42f2023-12-09 15:26:16 +0900788 optionsBuilder.addSubtype(
789 typeAndSubtype.second.get(0).substring(1));
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900790 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900791 mMdnsDiscoveryManager.registerListener(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900792 listenServiceType, listener, optionsBuilder.build());
Paul Hu508a0122023-09-11 15:31:33 +0800793 final ClientRequest request = storeDiscoveryManagerRequestMap(
794 clientRequestId, transactionId, listener, clientInfo,
795 info.getNetwork());
796 clientInfo.onDiscoverServicesStarted(clientRequestId, info, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000797 clientInfo.log("Register a DiscoveryListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +0000798 + " for service type:" + listenServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700799 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800800 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000801 if (discoverServices(transactionId, info)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800802 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +0000803 Log.d(TAG, "Discover " + msg.arg2 + " " + transactionId
Paul Hu23fa2022023-01-13 22:57:24 +0800804 + info.getServiceType());
805 }
Paul Hu508a0122023-09-11 15:31:33 +0800806 final ClientRequest request = storeLegacyRequestMap(clientRequestId,
807 transactionId, clientInfo, msg.what,
808 mClock.elapsedRealtime());
Paul Hu812e9212023-06-20 06:24:53 +0000809 clientInfo.onDiscoverServicesStarted(
Paul Hu508a0122023-09-11 15:31:33 +0800810 clientRequestId, info, request);
Paul Hu23fa2022023-01-13 22:57:24 +0800811 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000812 stopServiceDiscovery(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800813 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
814 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Paul Hu23fa2022023-01-13 22:57:24 +0800815 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700816 }
817 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800818 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900819 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800820 if (DBG) Log.d(TAG, "Stop service discovery");
Yuyang Huang86d083f2023-12-12 19:56:41 +0900821 final ListenerArgs args = (ListenerArgs) msg.obj;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900822 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000823 // If the binder death notification for a INsdManagerCallback was received
824 // before any calls are received by NsdService, the clientInfo would be
825 // cleared and cause NPE. Add a null check here to prevent this corner case.
826 if (clientInfo == null) {
827 Log.e(TAG, "Unknown connector in stop discovery");
828 break;
829 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700830
Paul Hud44e1b72023-06-16 02:07:42 +0000831 final ClientRequest request =
832 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900833 if (request == null) {
834 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700835 break;
836 }
Paul Hud44e1b72023-06-16 02:07:42 +0000837 transactionId = request.mTransactionId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900838 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
839 // point, so this needs to check the type of the original request to
840 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900841 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +0000842 stopDiscoveryManagerRequest(
843 request, clientRequestId, transactionId, clientInfo);
Paul Hu812e9212023-06-20 06:24:53 +0000844 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000845 clientInfo.log("Unregister the DiscoveryListener " + transactionId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700846 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000847 removeRequestMap(clientRequestId, transactionId, clientInfo);
848 if (stopServiceDiscovery(transactionId)) {
Paul Hu812e9212023-06-20 06:24:53 +0000849 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hu23fa2022023-01-13 22:57:24 +0800850 } else {
851 clientInfo.onStopDiscoveryFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000852 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu23fa2022023-01-13 22:57:24 +0800853 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700854 }
855 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900856 }
857 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800858 if (DBG) Log.d(TAG, "Register service");
Yuyang Huang86d083f2023-12-12 19:56:41 +0900859 final AdvertisingArgs args = (AdvertisingArgs) msg.obj;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900860 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000861 // If the binder death notification for a INsdManagerCallback was received
862 // before any calls are received by NsdService, the clientInfo would be
863 // cleared and cause NPE. Add a null check here to prevent this corner case.
864 if (clientInfo == null) {
865 Log.e(TAG, "Unknown connector in registration");
866 break;
867 }
868
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700869 if (requestLimitReached(clientInfo)) {
Paul Hu508a0122023-09-11 15:31:33 +0800870 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
871 NsdManager.FAILURE_MAX_LIMIT, true /* isLegacy */);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700872 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700873 }
Yuyang Huang86d083f2023-12-12 19:56:41 +0900874 final AdvertisingRequest advertisingRequest = args.advertisingRequest;
875 if (advertisingRequest == null) {
876 Log.e(TAG, "Unknown advertisingRequest in registration");
877 break;
878 }
879 final NsdServiceInfo serviceInfo = advertisingRequest.getServiceInfo();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900880 final String serviceType = serviceInfo.getServiceType();
Yuyang Huang170d42f2023-12-09 15:26:16 +0900881 final Pair<String, List<String>> typeSubtype = parseTypeAndSubtype(
882 serviceType);
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900883 final String registerServiceType = typeSubtype == null
884 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800885 if (clientInfo.mUseJavaBackend
886 || mDeps.isMdnsAdvertiserEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900887 || useAdvertiserForType(registerServiceType)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900888 if (registerServiceType == null) {
889 Log.e(TAG, "Invalid service type: " + serviceType);
Paul Hu508a0122023-09-11 15:31:33 +0800890 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
891 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900892 break;
893 }
Yuyang Huang86d083f2023-12-12 19:56:41 +0900894 boolean isUpdateOnly = (advertisingRequest.getAdvertisingConfig()
895 & AdvertisingRequest.NSD_ADVERTISING_UPDATE_ONLY) > 0;
896 // If it is an update request, then reuse the old transactionId
897 if (isUpdateOnly) {
898 final ClientRequest existingClientRequest =
899 clientInfo.mClientRequests.get(clientRequestId);
900 if (existingClientRequest == null) {
901 Log.e(TAG, "Invalid update on requestId: " + clientRequestId);
902 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
903 NsdManager.FAILURE_INTERNAL_ERROR,
904 false /* isLegacy */);
905 break;
906 }
907 transactionId = existingClientRequest.mTransactionId;
908 } else {
909 transactionId = getUniqueId();
910 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900911 serviceInfo.setServiceType(registerServiceType);
912 serviceInfo.setServiceName(truncateServiceName(
913 serviceInfo.getServiceName()));
914
Kangping Dong5af24b62023-12-10 21:41:16 +0800915 Set<String> subtypes = new ArraySet<>(serviceInfo.getSubtypes());
Yuyang Huang170d42f2023-12-09 15:26:16 +0900916 for (String subType: typeSubtype.second) {
917 if (!TextUtils.isEmpty(subType)) {
918 subtypes.add(subType);
919 }
Kangping Dong5af24b62023-12-10 21:41:16 +0800920 }
Kangping Dong5af24b62023-12-10 21:41:16 +0800921 subtypes = dedupSubtypeLabels(subtypes);
922
923 if (!checkSubtypeLabels(subtypes)) {
924 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
925 NsdManager.FAILURE_BAD_PARAMETERS, false /* isLegacy */);
926 break;
927 }
928
929 serviceInfo.setSubtypes(subtypes);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900930 maybeStartMonitoringSockets();
Yuyang Huang86d083f2023-12-12 19:56:41 +0900931 final MdnsAdvertisingOptions mdnsAdvertisingOptions =
932 MdnsAdvertisingOptions.newBuilder().setIsOnlyUpdate(
933 isUpdateOnly).build();
Yuyang Huange5cba9c2023-11-02 18:05:47 +0900934 mAdvertiser.addOrUpdateService(transactionId, serviceInfo,
Yuyang Huang86d083f2023-12-12 19:56:41 +0900935 mdnsAdvertisingOptions);
Paul Hud44e1b72023-06-16 02:07:42 +0000936 storeAdvertiserRequestMap(clientRequestId, transactionId, clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900937 serviceInfo.getNetwork());
Irfan Sheriff75006652012-04-17 23:15:29 -0700938 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900939 maybeStartDaemon();
Yuyang Huang86d083f2023-12-12 19:56:41 +0900940 transactionId = getUniqueId();
Paul Hud44e1b72023-06-16 02:07:42 +0000941 if (registerService(transactionId, serviceInfo)) {
942 if (DBG) {
943 Log.d(TAG, "Register " + clientRequestId
944 + " " + transactionId);
945 }
Paul Hua6bc4632023-06-26 01:18:29 +0000946 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
947 msg.what, mClock.elapsedRealtime());
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900948 // Return success after mDns reports success
949 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000950 unregisterService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800951 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
952 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900953 }
954
Irfan Sheriff75006652012-04-17 23:15:29 -0700955 }
956 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900957 }
958 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800959 if (DBG) Log.d(TAG, "unregister service");
Yuyang Huang86d083f2023-12-12 19:56:41 +0900960 final ListenerArgs args = (ListenerArgs) msg.obj;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900961 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000962 // If the binder death notification for a INsdManagerCallback was received
963 // before any calls are received by NsdService, the clientInfo would be
964 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900965 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800966 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700967 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700968 }
Paul Hud44e1b72023-06-16 02:07:42 +0000969 final ClientRequest request =
970 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900971 if (request == null) {
972 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
973 break;
974 }
Paul Hud44e1b72023-06-16 02:07:42 +0000975 transactionId = request.mTransactionId;
976 removeRequestMap(clientRequestId, transactionId, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900977
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900978 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
979 // so this needs to check the type of the original request to unregister
980 // instead of looking at the flag value.
981 if (request instanceof AdvertiserClientRequest) {
Paul Hu043bcd42023-07-14 16:38:25 +0800982 final AdvertiserMetrics metrics =
983 mAdvertiser.getAdvertiserMetrics(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +0000984 mAdvertiser.removeService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800985 clientInfo.onUnregisterServiceSucceeded(
986 clientRequestId, request, metrics);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700987 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000988 if (unregisterService(transactionId)) {
Paul Hu508a0122023-09-11 15:31:33 +0800989 clientInfo.onUnregisterServiceSucceeded(clientRequestId, request,
Paul Hu043bcd42023-07-14 16:38:25 +0800990 new AdvertiserMetrics(NO_PACKET /* repliedRequestsCount */,
991 NO_PACKET /* sentPacketCount */,
992 0 /* conflictDuringProbingCount */,
993 0 /* conflictAfterProbingCount */));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900994 } else {
995 clientInfo.onUnregisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000996 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900997 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700998 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700999 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001000 }
Paul Hu75069ed2023-01-14 00:31:09 +08001001 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +08001002 if (DBG) Log.d(TAG, "Resolve service");
Yuyang Huang86d083f2023-12-12 19:56:41 +09001003 final ListenerArgs args = (ListenerArgs) msg.obj;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001004 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +00001005 // If the binder death notification for a INsdManagerCallback was received
1006 // before any calls are received by NsdService, the clientInfo would be
1007 // cleared and cause NPE. Add a null check here to prevent this corner case.
1008 if (clientInfo == null) {
1009 Log.e(TAG, "Unknown connector in resolution");
1010 break;
1011 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001012
Paul Hu75069ed2023-01-14 00:31:09 +08001013 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001014 transactionId = getUniqueId();
Yuyang Huang170d42f2023-12-09 15:26:16 +09001015 final Pair<String, List<String>> typeSubtype =
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001016 parseTypeAndSubtype(info.getServiceType());
1017 final String serviceType = typeSubtype == null
1018 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001019 if (clientInfo.mUseJavaBackend
1020 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001021 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +08001022 if (serviceType == null) {
Paul Hu508a0122023-09-11 15:31:33 +08001023 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
1024 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +08001025 break;
1026 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001027 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +08001028
1029 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001030 final MdnsListener listener = new ResolutionListener(clientRequestId,
Kangping Dong97b2adc2024-01-11 16:00:37 +08001031 transactionId, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +08001032 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1033 .setNetwork(info.getNetwork())
1034 .setIsPassiveMode(true)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +09001035 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001036 .setRemoveExpiredService(true)
Paul Hu75069ed2023-01-14 00:31:09 +08001037 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001038 mMdnsDiscoveryManager.registerListener(
1039 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001040 storeDiscoveryManagerRequestMap(clientRequestId, transactionId,
1041 listener, clientInfo, info.getNetwork());
1042 clientInfo.log("Register a ResolutionListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001043 + " for service type:" + resolveServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -07001044 } else {
Paul Hu75069ed2023-01-14 00:31:09 +08001045 if (clientInfo.mResolvedService != null) {
Paul Hu508a0122023-09-11 15:31:33 +08001046 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
1047 NsdManager.FAILURE_ALREADY_ACTIVE, true /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +08001048 break;
1049 }
1050
1051 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +00001052 if (resolveService(transactionId, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +08001053 clientInfo.mResolvedService = new NsdServiceInfo();
Paul Hua6bc4632023-06-26 01:18:29 +00001054 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
1055 msg.what, mClock.elapsedRealtime());
Paul Hu75069ed2023-01-14 00:31:09 +08001056 } else {
Paul Hu508a0122023-09-11 15:31:33 +08001057 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
1058 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +08001059 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001060 }
1061 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001062 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001063 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +00001064 if (DBG) Log.d(TAG, "Stop service resolution");
Yuyang Huang86d083f2023-12-12 19:56:41 +09001065 final ListenerArgs args = (ListenerArgs) msg.obj;
Paul Hub58deb72022-12-26 09:24:42 +00001066 clientInfo = mClients.get(args.connector);
1067 // If the binder death notification for a INsdManagerCallback was received
1068 // before any calls are received by NsdService, the clientInfo would be
1069 // cleared and cause NPE. Add a null check here to prevent this corner case.
1070 if (clientInfo == null) {
1071 Log.e(TAG, "Unknown connector in stop resolution");
1072 break;
1073 }
1074
Paul Hud44e1b72023-06-16 02:07:42 +00001075 final ClientRequest request =
1076 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001077 if (request == null) {
1078 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
1079 break;
1080 }
Paul Hud44e1b72023-06-16 02:07:42 +00001081 transactionId = request.mTransactionId;
Paul Hue4f5f252023-02-16 21:13:47 +08001082 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
1083 // point, so this needs to check the type of the original request to
1084 // unregister instead of looking at the flag value.
1085 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001086 stopDiscoveryManagerRequest(
1087 request, clientRequestId, transactionId, clientInfo);
Paul Hu60149052023-07-31 14:26:08 +08001088 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001089 clientInfo.log("Unregister the ResolutionListener " + transactionId);
Paul Hub58deb72022-12-26 09:24:42 +00001090 } else {
Paul Hud44e1b72023-06-16 02:07:42 +00001091 removeRequestMap(clientRequestId, transactionId, clientInfo);
1092 if (stopResolveService(transactionId)) {
Paul Hu60149052023-07-31 14:26:08 +08001093 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hue4f5f252023-02-16 21:13:47 +08001094 } else {
1095 clientInfo.onStopResolutionFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001096 clientRequestId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hue4f5f252023-02-16 21:13:47 +08001097 }
1098 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +00001099 }
Paul Hub58deb72022-12-26 09:24:42 +00001100 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001101 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001102 case NsdManager.REGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001103 if (DBG) Log.d(TAG, "Register a service callback");
Yuyang Huang86d083f2023-12-12 19:56:41 +09001104 final ListenerArgs args = (ListenerArgs) msg.obj;
Paul Hu18aeccc2022-12-27 08:48:48 +00001105 clientInfo = mClients.get(args.connector);
1106 // If the binder death notification for a INsdManagerCallback was received
1107 // before any calls are received by NsdService, the clientInfo would be
1108 // cleared and cause NPE. Add a null check here to prevent this corner case.
1109 if (clientInfo == null) {
1110 Log.e(TAG, "Unknown connector in callback registration");
1111 break;
1112 }
1113
Paul Hu30bd70d2023-02-07 13:20:56 +00001114 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001115 transactionId = getUniqueId();
Yuyang Huang170d42f2023-12-09 15:26:16 +09001116 final Pair<String, List<String>> typeAndSubtype =
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001117 parseTypeAndSubtype(info.getServiceType());
1118 final String serviceType = typeAndSubtype == null
1119 ? null : typeAndSubtype.first;
Paul Hu30bd70d2023-02-07 13:20:56 +00001120 if (serviceType == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001121 clientInfo.onServiceInfoCallbackRegistrationFailed(clientRequestId,
Paul Hu30bd70d2023-02-07 13:20:56 +00001122 NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +00001123 break;
1124 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001125 final String resolveServiceType = serviceType + ".local";
Paul Hu18aeccc2022-12-27 08:48:48 +00001126
Paul Hu30bd70d2023-02-07 13:20:56 +00001127 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001128 final MdnsListener listener = new ServiceInfoListener(clientRequestId,
Kangping Dong97b2adc2024-01-11 16:00:37 +08001129 transactionId, resolveServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +00001130 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1131 .setNetwork(info.getNetwork())
1132 .setIsPassiveMode(true)
1133 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001134 .setRemoveExpiredService(true)
Paul Hu30bd70d2023-02-07 13:20:56 +00001135 .build();
1136 mMdnsDiscoveryManager.registerListener(
1137 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001138 storeDiscoveryManagerRequestMap(clientRequestId, transactionId, listener,
1139 clientInfo, info.getNetwork());
Paul Huddce5912023-08-01 10:26:49 +08001140 clientInfo.onServiceInfoCallbackRegistered(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00001141 clientInfo.log("Register a ServiceInfoListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001142 + " for service type:" + resolveServiceType);
Paul Hu18aeccc2022-12-27 08:48:48 +00001143 break;
Paul Hu30bd70d2023-02-07 13:20:56 +00001144 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001145 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001146 if (DBG) Log.d(TAG, "Unregister a service callback");
Yuyang Huang86d083f2023-12-12 19:56:41 +09001147 final ListenerArgs args = (ListenerArgs) msg.obj;
Paul Hu18aeccc2022-12-27 08:48:48 +00001148 clientInfo = mClients.get(args.connector);
1149 // If the binder death notification for a INsdManagerCallback was received
1150 // before any calls are received by NsdService, the clientInfo would be
1151 // cleared and cause NPE. Add a null check here to prevent this corner case.
1152 if (clientInfo == null) {
1153 Log.e(TAG, "Unknown connector in callback unregistration");
1154 break;
1155 }
1156
Paul Hud44e1b72023-06-16 02:07:42 +00001157 final ClientRequest request =
1158 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001159 if (request == null) {
Paul Hu30bd70d2023-02-07 13:20:56 +00001160 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE_CALLBACK");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001161 break;
1162 }
Paul Hud44e1b72023-06-16 02:07:42 +00001163 transactionId = request.mTransactionId;
Paul Hu30bd70d2023-02-07 13:20:56 +00001164 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001165 stopDiscoveryManagerRequest(
1166 request, clientRequestId, transactionId, clientInfo);
Paul Huddce5912023-08-01 10:26:49 +08001167 clientInfo.onServiceInfoCallbackUnregistered(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001168 clientInfo.log("Unregister the ServiceInfoListener " + transactionId);
Paul Hu18aeccc2022-12-27 08:48:48 +00001169 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001170 loge("Unregister failed with non-DiscoveryManagerRequest.");
Paul Hu18aeccc2022-12-27 08:48:48 +00001171 }
Paul Hu18aeccc2022-12-27 08:48:48 +00001172 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001173 }
paulhu2b9ed952022-02-10 21:58:32 +08001174 case MDNS_SERVICE_EVENT:
1175 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +09001176 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001177 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001178 break;
Paul Hu019621e2023-01-13 23:26:49 +08001179 case MDNS_DISCOVERY_MANAGER_EVENT:
1180 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
1181 return NOT_HANDLED;
1182 }
1183 break;
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001184 case NsdManager.REGISTER_OFFLOAD_ENGINE:
1185 offloadEngineInfo = (OffloadEngineInfo) msg.obj;
1186 // TODO: Limits the number of registrations created by a given class.
1187 mOffloadEngines.register(offloadEngineInfo.mOffloadEngine,
1188 offloadEngineInfo);
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001189 sendAllOffloadServiceInfos(offloadEngineInfo);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001190 break;
1191 case NsdManager.UNREGISTER_OFFLOAD_ENGINE:
1192 mOffloadEngines.unregister((IOffloadEngine) msg.obj);
1193 break;
Paul Hu77c11182023-10-23 16:17:32 +08001194 case NsdManager.REGISTER_CLIENT:
1195 final ConnectorArgs arg = (ConnectorArgs) msg.obj;
1196 final INsdManagerCallback cb = arg.callback;
1197 try {
1198 cb.asBinder().linkToDeath(arg.connector, 0);
1199 final String tag = "Client" + arg.uid + "-" + mClientNumberId++;
1200 final NetworkNsdReportedMetrics metrics =
1201 mDeps.makeNetworkNsdReportedMetrics(
1202 (int) mClock.elapsedRealtime());
1203 clientInfo = new ClientInfo(cb, arg.uid, arg.useJavaBackend,
1204 mServiceLogs.forSubComponent(tag), metrics);
1205 mClients.put(arg.connector, clientInfo);
1206 } catch (RemoteException e) {
1207 Log.w(TAG, "Client request id " + clientRequestId
1208 + " has already died");
1209 }
1210 break;
1211 case NsdManager.UNREGISTER_CLIENT:
1212 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
1213 clientInfo = mClients.remove(connector);
1214 if (clientInfo != null) {
1215 clientInfo.expungeAllRequests();
1216 if (clientInfo.isPreSClient()) {
1217 mLegacyClientCount -= 1;
1218 }
1219 }
1220 maybeStopMonitoringSocketsIfNoActiveRequest();
1221 maybeScheduleStop();
1222 break;
1223 case NsdManager.DAEMON_CLEANUP:
1224 maybeStopDaemon();
1225 break;
1226 // This event should be only sent by the legacy (target SDK < S) clients.
1227 // Mark the sending client as legacy.
1228 case NsdManager.DAEMON_STARTUP:
1229 clientInfo = getClientInfoForReply(msg);
1230 if (clientInfo != null) {
1231 cancelStop();
1232 clientInfo.setPreSClient();
1233 mLegacyClientCount += 1;
1234 maybeStartDaemon();
1235 }
1236 break;
Irfan Sheriff75006652012-04-17 23:15:29 -07001237 default:
Paul Hu77c11182023-10-23 16:17:32 +08001238 Log.wtf(TAG, "Unhandled " + msg);
Hugo Benichif0c84092017-04-05 14:43:29 +09001239 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001240 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001241 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001242 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001243
Paul Hud44e1b72023-06-16 02:07:42 +00001244 private boolean handleMDnsServiceEvent(int code, int transactionId, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001245 NsdServiceInfo servInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001246 ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001247 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001248 Log.e(TAG, String.format(
1249 "transactionId %d for %d has no client mapping", transactionId, code));
Hugo Benichif0c84092017-04-05 14:43:29 +09001250 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001251 }
1252
1253 /* This goes in response as msg.arg2 */
Paul Hud44e1b72023-06-16 02:07:42 +00001254 int clientRequestId = clientInfo.getClientRequestId(transactionId);
1255 if (clientRequestId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -07001256 // This can happen because of race conditions. For example,
1257 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
1258 // and we may get in this situation.
Paul Hud44e1b72023-06-16 02:07:42 +00001259 Log.d(TAG, String.format("%d for transactionId %d that is no longer active",
1260 code, transactionId));
Hugo Benichif0c84092017-04-05 14:43:29 +09001261 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001262 }
Paul Hu812e9212023-06-20 06:24:53 +00001263 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1264 if (request == null) {
1265 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1266 return false;
1267 }
Hugo Benichi32be63d2017-04-05 14:06:11 +09001268 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00001269 Log.d(TAG, String.format(
1270 "MDns service event code:%d transactionId=%d", code, transactionId));
Hugo Benichi32be63d2017-04-05 14:06:11 +09001271 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001272 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +08001273 case IMDnsEventListener.SERVICE_FOUND: {
1274 final DiscoveryInfo info = (DiscoveryInfo) obj;
1275 final String name = info.serviceName;
1276 final String type = info.registrationType;
1277 servInfo = new NsdServiceInfo(name, type);
1278 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001279 if (foundNetId == 0L) {
1280 // Ignore services that do not have a Network: they are not usable
1281 // by apps, as they would need privileged permissions to use
1282 // interfaces that do not have an associated Network.
1283 break;
1284 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +09001285 if (foundNetId == INetd.DUMMY_NET_ID) {
1286 // Ignore services on the dummy0 interface: they are only seen when
1287 // discovering locally advertised services, and are not reachable
1288 // through that interface.
1289 break;
1290 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001291 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001292
1293 clientInfo.onServiceFound(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001294 break;
paulhu2b9ed952022-02-10 21:58:32 +08001295 }
1296 case IMDnsEventListener.SERVICE_LOST: {
1297 final DiscoveryInfo info = (DiscoveryInfo) obj;
1298 final String name = info.serviceName;
1299 final String type = info.registrationType;
1300 final int lostNetId = info.netId;
1301 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001302 // The network could be set to null (netId 0) if it was torn down when the
1303 // service is lost
1304 // TODO: avoid returning null in that case, possibly by remembering
1305 // found services on the same interface index and their network at the time
1306 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001307 clientInfo.onServiceLost(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001308 break;
paulhu2b9ed952022-02-10 21:58:32 +08001309 }
1310 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Paul Hu812e9212023-06-20 06:24:53 +00001311 clientInfo.onDiscoverServicesFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001312 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1313 transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001314 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001315 break;
paulhu2b9ed952022-02-10 21:58:32 +08001316 case IMDnsEventListener.SERVICE_REGISTERED: {
1317 final RegistrationInfo info = (RegistrationInfo) obj;
1318 final String name = info.serviceName;
1319 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Paul Hu508a0122023-09-11 15:31:33 +08001320 clientInfo.onRegisterServiceSucceeded(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001321 break;
paulhu2b9ed952022-02-10 21:58:32 +08001322 }
1323 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Paul Hu777ed052023-06-19 13:35:15 +00001324 clientInfo.onRegisterServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001325 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1326 transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001327 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001328 break;
paulhu2b9ed952022-02-10 21:58:32 +08001329 case IMDnsEventListener.SERVICE_RESOLVED: {
1330 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001331 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +08001332 final String fullName = info.serviceFullName;
1333 while (index < fullName.length() && fullName.charAt(index) != '.') {
1334 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001335 ++index;
1336 }
1337 ++index;
1338 }
paulhu2b9ed952022-02-10 21:58:32 +08001339 if (index >= fullName.length()) {
1340 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001341 break;
1342 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001343
paulhube186602022-04-12 07:18:23 +00001344 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001345 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001346 String type = rest.replace(".local.", "");
1347
Paul Hu30bd70d2023-02-07 13:20:56 +00001348 final NsdServiceInfo serviceInfo = clientInfo.mResolvedService;
Paul Hu18aeccc2022-12-27 08:48:48 +00001349 serviceInfo.setServiceName(name);
1350 serviceInfo.setServiceType(type);
1351 serviceInfo.setPort(info.port);
1352 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001353 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001354
Paul Hud44e1b72023-06-16 02:07:42 +00001355 stopResolveService(transactionId);
1356 removeRequestMap(clientRequestId, transactionId, clientInfo);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001357
Paul Hud44e1b72023-06-16 02:07:42 +00001358 final int transactionId2 = getUniqueId();
1359 if (getAddrInfo(transactionId2, info.hostname, info.interfaceIdx)) {
1360 storeLegacyRequestMap(clientRequestId, transactionId2, clientInfo,
Paul Hua6bc4632023-06-26 01:18:29 +00001361 NsdManager.RESOLVE_SERVICE, request.mStartTimeMs);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001362 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001363 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001364 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1365 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001366 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001367 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001368 }
1369 break;
paulhu2b9ed952022-02-10 21:58:32 +08001370 }
1371 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001372 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001373 stopResolveService(transactionId);
1374 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001375 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001376 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1377 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001378 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001379 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001380 break;
paulhu2b9ed952022-02-10 21:58:32 +08001381 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001382 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001383 stopGetAddrInfo(transactionId);
1384 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001385 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001386 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1387 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001388 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001389 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001390 break;
paulhu2b9ed952022-02-10 21:58:32 +08001391 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001392 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001393 final GetAddressInfo info = (GetAddressInfo) obj;
1394 final String address = info.address;
1395 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001396 InetAddress serviceHost = null;
1397 try {
paulhu2b9ed952022-02-10 21:58:32 +08001398 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001399 } catch (UnknownHostException e) {
1400 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1401 }
1402
1403 // If the resolved service is on an interface without a network, consider it
1404 // as a failure: it would not be usable by apps as they would need
1405 // privileged permissions.
Paul Hu30bd70d2023-02-07 13:20:56 +00001406 if (netId != NETID_UNSET && serviceHost != null) {
1407 clientInfo.mResolvedService.setHost(serviceHost);
1408 setServiceNetworkForCallback(clientInfo.mResolvedService,
1409 netId, info.interfaceIdx);
1410 clientInfo.onResolveServiceSucceeded(
Paul Hua6bc4632023-06-26 01:18:29 +00001411 clientRequestId, clientInfo.mResolvedService, request);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001412 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001413 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001414 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1415 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001416 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001417 }
Paul Hud44e1b72023-06-16 02:07:42 +00001418 stopGetAddrInfo(transactionId);
1419 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001420 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001421 break;
paulhu2b9ed952022-02-10 21:58:32 +08001422 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001423 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001424 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001425 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001426 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001427 }
Paul Hu019621e2023-01-13 23:26:49 +08001428
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001429 @Nullable
1430 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(
1431 final MdnsEvent event, int code) {
Paul Hu019621e2023-01-13 23:26:49 +08001432 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001433 final String[] typeArray = serviceInfo.getServiceType();
1434 final String joinedType;
1435 if (typeArray.length == 0
1436 || !typeArray[typeArray.length - 1].equals(LOCAL_DOMAIN_NAME)) {
1437 Log.wtf(TAG, "MdnsServiceInfo type does not end in .local: "
1438 + Arrays.toString(typeArray));
1439 return null;
1440 } else {
1441 joinedType = TextUtils.join(".",
1442 Arrays.copyOfRange(typeArray, 0, typeArray.length - 1));
1443 }
1444 final String serviceType;
1445 switch (code) {
1446 case NsdManager.SERVICE_FOUND:
1447 case NsdManager.SERVICE_LOST:
1448 // For consistency with historical behavior, discovered service types have
1449 // a dot at the end.
1450 serviceType = joinedType + ".";
1451 break;
1452 case RESOLVE_SERVICE_SUCCEEDED:
1453 // For consistency with historical behavior, resolved service types have
1454 // a dot at the beginning.
1455 serviceType = "." + joinedType;
1456 break;
1457 default:
1458 serviceType = joinedType;
1459 break;
1460 }
Paul Hu019621e2023-01-13 23:26:49 +08001461 final String serviceName = serviceInfo.getServiceInstanceName();
1462 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1463 final Network network = serviceInfo.getNetwork();
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001464 // In MdnsDiscoveryManagerEvent, the Network can be null which means it is a
1465 // network for Tethering interface. In other words, the network == null means the
1466 // network has netId = INetd.LOCAL_NET_ID.
Paul Hu019621e2023-01-13 23:26:49 +08001467 setServiceNetworkForCallback(
1468 servInfo,
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001469 network == null ? INetd.LOCAL_NET_ID : network.netId,
Paul Hu019621e2023-01-13 23:26:49 +08001470 serviceInfo.getInterfaceIndex());
Kangping Dong5af24b62023-12-10 21:41:16 +08001471 servInfo.setSubtypes(dedupSubtypeLabels(serviceInfo.getSubtypes()));
Paul Hu019621e2023-01-13 23:26:49 +08001472 return servInfo;
1473 }
1474
1475 private boolean handleMdnsDiscoveryManagerEvent(
1476 int transactionId, int code, Object obj) {
Paul Hud44e1b72023-06-16 02:07:42 +00001477 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Paul Hu019621e2023-01-13 23:26:49 +08001478 if (clientInfo == null) {
1479 Log.e(TAG, String.format(
1480 "id %d for %d has no client mapping", transactionId, code));
1481 return false;
1482 }
1483
1484 final MdnsEvent event = (MdnsEvent) obj;
Paul Hud44e1b72023-06-16 02:07:42 +00001485 final int clientRequestId = event.mClientRequestId;
Paul Hubad6fe92023-07-24 21:25:22 +08001486 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1487 if (request == null) {
1488 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1489 return false;
1490 }
1491
1492 // Deal with the discovery sent callback
1493 if (code == DISCOVERY_QUERY_SENT_CALLBACK) {
1494 request.onQuerySent();
1495 return true;
1496 }
1497
1498 // Deal with other callbacks.
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001499 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event, code);
1500 // Errors are already logged if null
1501 if (info == null) return false;
Paul Hu83ec7f42023-06-07 18:04:09 +08001502 mServiceLogs.log(String.format(
1503 "MdnsDiscoveryManager event code=%s transactionId=%d",
1504 NsdManager.nameOf(code), transactionId));
Paul Hu019621e2023-01-13 23:26:49 +08001505 switch (code) {
1506 case NsdManager.SERVICE_FOUND:
Paul Hu812e9212023-06-20 06:24:53 +00001507 clientInfo.onServiceFound(clientRequestId, info, request);
Paul Hu319751a2023-01-13 23:56:34 +08001508 break;
1509 case NsdManager.SERVICE_LOST:
Paul Hu812e9212023-06-20 06:24:53 +00001510 clientInfo.onServiceLost(clientRequestId, info, request);
Paul Hu019621e2023-01-13 23:26:49 +08001511 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001512 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
1513 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Paul Hu75069ed2023-01-14 00:31:09 +08001514 info.setPort(serviceInfo.getPort());
1515
1516 Map<String, String> attrs = serviceInfo.getAttributes();
1517 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1518 final String key = kv.getKey();
1519 try {
1520 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1521 } catch (IllegalArgumentException e) {
1522 Log.e(TAG, "Invalid attribute", e);
1523 }
1524 }
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001525 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu2b865912023-03-06 14:27:53 +08001526 if (addresses.size() != 0) {
1527 info.setHostAddresses(addresses);
Paul Hua6bc4632023-06-26 01:18:29 +00001528 request.setServiceFromCache(event.mIsServiceFromCache);
1529 clientInfo.onResolveServiceSucceeded(clientRequestId, info, request);
Paul Hu2b865912023-03-06 14:27:53 +08001530 } else {
1531 // No address. Notify resolution failure.
Paul Hua6bc4632023-06-26 01:18:29 +00001532 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001533 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */,
1534 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001535 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu75069ed2023-01-14 00:31:09 +08001536 }
1537
1538 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001539 if (!(request instanceof DiscoveryManagerRequest)) {
1540 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1541 break;
1542 }
Paul Hud44e1b72023-06-16 02:07:42 +00001543 stopDiscoveryManagerRequest(
1544 request, clientRequestId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001545 break;
1546 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001547 case NsdManager.SERVICE_UPDATED: {
1548 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1549 info.setPort(serviceInfo.getPort());
1550
1551 Map<String, String> attrs = serviceInfo.getAttributes();
1552 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1553 final String key = kv.getKey();
1554 try {
1555 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1556 } catch (IllegalArgumentException e) {
1557 Log.e(TAG, "Invalid attribute", e);
1558 }
1559 }
1560
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001561 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001562 info.setHostAddresses(addresses);
Paul Huddce5912023-08-01 10:26:49 +08001563 clientInfo.onServiceUpdated(clientRequestId, info, request);
1564 // Set the ServiceFromCache flag only if the service is actually being
1565 // retrieved from the cache. This flag should not be overridden by later
1566 // service updates, which may not be cached.
1567 if (event.mIsServiceFromCache) {
1568 request.setServiceFromCache(true);
1569 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001570 break;
1571 }
1572 case NsdManager.SERVICE_UPDATED_LOST:
Paul Huddce5912023-08-01 10:26:49 +08001573 clientInfo.onServiceUpdatedLost(clientRequestId, request);
Paul Hu30bd70d2023-02-07 13:20:56 +00001574 break;
Paul Hu019621e2023-01-13 23:26:49 +08001575 default:
1576 return false;
1577 }
1578 return true;
1579 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001580 }
1581 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001582
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001583 @NonNull
1584 private static List<InetAddress> getInetAddresses(@NonNull MdnsServiceInfo serviceInfo) {
1585 final List<String> v4Addrs = serviceInfo.getIpv4Addresses();
1586 final List<String> v6Addrs = serviceInfo.getIpv6Addresses();
1587 final List<InetAddress> addresses = new ArrayList<>(v4Addrs.size() + v6Addrs.size());
1588 for (String ipv4Address : v4Addrs) {
1589 try {
1590 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1591 } catch (IllegalArgumentException e) {
1592 Log.wtf(TAG, "Invalid ipv4 address", e);
1593 }
1594 }
1595 for (String ipv6Address : v6Addrs) {
1596 try {
Yuyang Huanga6a6ff92023-04-24 13:33:34 +09001597 final Inet6Address addr = (Inet6Address) InetAddresses.parseNumericAddress(
1598 ipv6Address);
1599 addresses.add(InetAddressUtils.withScopeId(addr, serviceInfo.getInterfaceIndex()));
1600 } catch (IllegalArgumentException e) {
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001601 Log.wtf(TAG, "Invalid ipv6 address", e);
1602 }
1603 }
1604 return addresses;
1605 }
1606
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001607 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1608 switch (netId) {
1609 case NETID_UNSET:
1610 info.setNetwork(null);
1611 break;
1612 case INetd.LOCAL_NET_ID:
1613 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1614 // visible / usable for apps, so do not return it. Store the interface
1615 // index instead, so at least if the client tries to resolve the service
1616 // with that NsdServiceInfo, it will be done on the same interface.
1617 // If they recreate the NsdServiceInfo themselves, resolution would be
1618 // done on all interfaces as before T, which should also work.
1619 info.setNetwork(null);
1620 info.setInterfaceIndex(ifaceIdx);
1621 break;
1622 default:
1623 info.setNetwork(new Network(netId));
1624 }
1625 }
1626
paulhube186602022-04-12 07:18:23 +00001627 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1628 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1629 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1630 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1631 private String unescape(String s) {
1632 StringBuilder sb = new StringBuilder(s.length());
1633 for (int i = 0; i < s.length(); ++i) {
1634 char c = s.charAt(i);
1635 if (c == '\\') {
1636 if (++i >= s.length()) {
1637 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1638 break;
1639 }
1640 c = s.charAt(i);
1641 if (c != '.' && c != '\\') {
1642 if (i + 2 >= s.length()) {
1643 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1644 break;
1645 }
1646 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1647 + (s.charAt(i + 2) - '0'));
1648 i += 2;
1649 }
1650 }
1651 sb.append(c);
1652 }
1653 return sb.toString();
1654 }
1655
Paul Hu7445e3d2023-03-03 15:14:00 +08001656 /**
1657 * Check the given service type is valid and construct it to a service type
1658 * which can use for discovery / resolution service.
1659 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001660 * <p>The valid service type should be 2 labels, or 3 labels if the query is for a
Paul Hu7445e3d2023-03-03 15:14:00 +08001661 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1662 * underscore; they are alphanumerical characters or dashes or underscore, except the
1663 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1664 *
Yuyang Huang170d42f2023-12-09 15:26:16 +09001665 * <p>The subtypes may also be specified with a comma after the service type, for example
1666 * _type._tcp,_subtype1,_subtype2
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001667 *
Paul Hu7445e3d2023-03-03 15:14:00 +08001668 * @param serviceType the request service type for discovery / resolution service
1669 * @return constructed service type or null if the given service type is invalid.
1670 */
1671 @Nullable
Yuyang Huang170d42f2023-12-09 15:26:16 +09001672 public static Pair<String, List<String>> parseTypeAndSubtype(String serviceType) {
Paul Hu7445e3d2023-03-03 15:14:00 +08001673 if (TextUtils.isEmpty(serviceType)) return null;
Yuyang Huang86d083f2023-12-12 19:56:41 +09001674 final Pattern serviceTypePattern = Pattern.compile(TYPE_REGEX);
Paul Hu7445e3d2023-03-03 15:14:00 +08001675 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1676 if (!matcher.matches()) return null;
Yuyang Huang170d42f2023-12-09 15:26:16 +09001677 final String queryType = matcher.group(2);
1678 // Use the subtype at the beginning
1679 if (matcher.group(1) != null) {
1680 return new Pair<>(queryType, List.of(matcher.group(1)));
1681 }
1682 // Use the subtypes at the end
1683 final String subTypesStr = matcher.group(3);
1684 if (subTypesStr != null && !subTypesStr.isEmpty()) {
1685 final String[] subTypes = subTypesStr.substring(1).split(",");
1686 return new Pair<>(queryType, List.of(subTypes));
1687 }
1688
1689 return new Pair<>(queryType, Collections.emptyList());
Paul Hu7445e3d2023-03-03 15:14:00 +08001690 }
1691
Kangping Dong5af24b62023-12-10 21:41:16 +08001692 /** Returns {@code true} if {@code subtype} is a valid DNS-SD subtype label. */
1693 private static boolean checkSubtypeLabel(String subtype) {
1694 return Pattern.compile("^" + TYPE_SUBTYPE_LABEL_REGEX + "$").matcher(subtype).matches();
1695 }
1696
Hugo Benichi803a2f02017-04-24 11:35:06 +09001697 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001698 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001699 this(ctx, handler, cleanupDelayMs, new Dependencies());
1700 }
1701
1702 @VisibleForTesting
1703 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001704 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001705 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001706 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001707 mNsdStateMachine.start();
Ken Chen80c9f6f2023-11-15 18:24:54 +08001708 // It can fail on V+ device since mdns native service provided by netd is removed.
1709 mMDnsManager = SdkLevel.isAtLeastV() ? null : ctx.getSystemService(MDnsManager.class);
paulhu2b9ed952022-02-10 21:58:32 +08001710 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001711 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001712
Paul Hu14667de2023-04-17 22:42:47 +08001713 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper(),
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001714 LOGGER.forSubComponent("MdnsSocketProvider"), new SocketRequestMonitor());
Yuyang Huang700778b2023-03-08 16:17:05 +09001715 // Netlink monitor starts on boot, and intentionally never stopped, to ensure that all
Yuyang Huangfca402a2023-05-24 14:45:59 +09001716 // address events are received. When the netlink monitor starts, any IP addresses already
1717 // on the interfaces will not be seen. In practice, the network will not connect at boot
1718 // time As a result, all the netlink message should be observed if the netlink monitor
1719 // starts here.
Yuyang Huang700778b2023-03-08 16:17:05 +09001720 handler.post(mMdnsSocketProvider::startNetLinkMonitor);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001721
1722 // NsdService is started after ActivityManager (startOtherServices in SystemServer, vs.
1723 // startBootstrapServices).
1724 mRunningAppActiveImportanceCutoff = mDeps.getDeviceConfigInt(
1725 MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF,
1726 DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF);
1727 final ActivityManager am = ctx.getSystemService(ActivityManager.class);
1728 am.addOnUidImportanceListener(new UidImportanceListener(handler),
1729 mRunningAppActiveImportanceCutoff);
1730
Paul Huf3fe3332023-10-16 17:13:25 +08001731 final MdnsFeatureFlags flags = new MdnsFeatureFlags.Builder()
1732 .setIsMdnsOffloadFeatureEnabled(mDeps.isTetheringFeatureNotChickenedOut(
1733 mContext, MdnsFeatureFlags.NSD_FORCE_DISABLE_MDNS_OFFLOAD))
1734 .setIncludeInetAddressRecordsInProbing(mDeps.isFeatureEnabled(
1735 mContext, MdnsFeatureFlags.INCLUDE_INET_ADDRESS_RECORDS_IN_PROBING))
Paul Hu596a5002023-10-18 17:07:31 +08001736 .setIsExpiredServicesRemovalEnabled(mDeps.isFeatureEnabled(
1737 mContext, MdnsFeatureFlags.NSD_EXPIRED_SERVICES_REMOVAL))
Paul Hufd357ef2023-11-01 16:32:45 +08001738 .setIsLabelCountLimitEnabled(mDeps.isTetheringFeatureNotChickenedOut(
1739 mContext, MdnsFeatureFlags.NSD_LIMIT_LABEL_COUNT))
Paul Hu01f243f2023-11-22 17:26:36 +08001740 .setIsKnownAnswerSuppressionEnabled(mDeps.isFeatureEnabled(
1741 mContext, MdnsFeatureFlags.NSD_KNOWN_ANSWER_SUPPRESSION))
Paul Huf3fe3332023-10-16 17:13:25 +08001742 .build();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001743 mMdnsSocketClient =
Yuyang Huang7ddf2932023-08-01 18:16:30 +09001744 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider,
Paul Hufd357ef2023-11-01 16:32:45 +08001745 LOGGER.forSubComponent("MdnsMultinetworkSocketClient"), flags);
Paul Hu14667de2023-04-17 22:42:47 +08001746 mMdnsDiscoveryManager = deps.makeMdnsDiscoveryManager(new ExecutorProvider(),
Paul Huf3fe3332023-10-16 17:13:25 +08001747 mMdnsSocketClient, LOGGER.forSubComponent("MdnsDiscoveryManager"), flags);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001748 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1749 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
Yuyang Huangb96a0712023-09-07 15:13:15 +09001750 new AdvertiserCallback(), LOGGER.forSubComponent("MdnsAdvertiser"), flags);
Paul Hu777ed052023-06-19 13:35:15 +00001751 mClock = deps.makeClock();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001752 }
1753
1754 /**
1755 * Dependencies of NsdService, for injection in tests.
1756 */
1757 @VisibleForTesting
1758 public static class Dependencies {
1759 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001760 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001761 *
1762 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001763 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001764 */
1765 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001766 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001767 MDNS_DISCOVERY_MANAGER_VERSION);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001768 }
1769
1770 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001771 * Check whether the MdnsAdvertiser feature is enabled.
1772 *
1773 * @param context The global context information about an app environment.
1774 * @return true if the MdnsAdvertiser feature is enabled.
1775 */
1776 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001777 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001778 MDNS_ADVERTISER_VERSION);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001779 }
1780
1781 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001782 * Get the type allowlist flag value.
1783 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1784 */
1785 @Nullable
1786 public String getTypeAllowlistFlags() {
1787 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1788 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1789 }
1790
1791 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001792 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001793 */
1794 public boolean isFeatureEnabled(Context context, String feature) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001795 return DeviceConfigUtils.isTetheringFeatureEnabled(context, feature);
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001796 }
1797
1798 /**
Yuyang Huangb96a0712023-09-07 15:13:15 +09001799 * @see DeviceConfigUtils#isTetheringFeatureNotChickenedOut
1800 */
Motomu Utsumied4e7ec2023-09-13 14:58:32 +09001801 public boolean isTetheringFeatureNotChickenedOut(Context context, String feature) {
1802 return DeviceConfigUtils.isTetheringFeatureNotChickenedOut(context, feature);
Yuyang Huangb96a0712023-09-07 15:13:15 +09001803 }
1804
1805 /**
Paul Huf3fe3332023-10-16 17:13:25 +08001806 * @see DeviceConfigUtils#isTrunkStableFeatureEnabled
1807 */
1808 public boolean isTrunkStableFeatureEnabled(String feature) {
1809 return DeviceConfigUtils.isTrunkStableFeatureEnabled(feature);
1810 }
1811
1812 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001813 * @see MdnsDiscoveryManager
1814 */
1815 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
Paul Hu14667de2023-04-17 22:42:47 +08001816 @NonNull ExecutorProvider executorProvider,
Paul Huf3fe3332023-10-16 17:13:25 +08001817 @NonNull MdnsMultinetworkSocketClient socketClient, @NonNull SharedLog sharedLog,
1818 @NonNull MdnsFeatureFlags featureFlags) {
1819 return new MdnsDiscoveryManager(
1820 executorProvider, socketClient, sharedLog, featureFlags);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001821 }
1822
1823 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001824 * @see MdnsAdvertiser
1825 */
1826 public MdnsAdvertiser makeMdnsAdvertiser(
1827 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
Yuyang Huangb96a0712023-09-07 15:13:15 +09001828 @NonNull MdnsAdvertiser.AdvertiserCallback cb, @NonNull SharedLog sharedLog,
1829 MdnsFeatureFlags featureFlags) {
1830 return new MdnsAdvertiser(looper, socketProvider, cb, sharedLog, featureFlags);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001831 }
1832
1833 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001834 * @see MdnsSocketProvider
1835 */
Paul Hu14667de2023-04-17 22:42:47 +08001836 public MdnsSocketProvider makeMdnsSocketProvider(@NonNull Context context,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001837 @NonNull Looper looper, @NonNull SharedLog sharedLog,
1838 @NonNull MdnsSocketProvider.SocketRequestMonitor socketCreationCallback) {
1839 return new MdnsSocketProvider(context, looper, sharedLog, socketCreationCallback);
1840 }
1841
1842 /**
1843 * @see DeviceConfig#getInt(String, String, int)
1844 */
1845 public int getDeviceConfigInt(@NonNull String config, int defaultValue) {
1846 return DeviceConfig.getInt(NAMESPACE_TETHERING, config, defaultValue);
1847 }
1848
1849 /**
1850 * @see Binder#getCallingUid()
1851 */
1852 public int getCallingUid() {
1853 return Binder.getCallingUid();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001854 }
Paul Hu777ed052023-06-19 13:35:15 +00001855
1856 /**
1857 * @see NetworkNsdReportedMetrics
1858 */
Paul Hu508a0122023-09-11 15:31:33 +08001859 public NetworkNsdReportedMetrics makeNetworkNsdReportedMetrics(int clientId) {
1860 return new NetworkNsdReportedMetrics(clientId);
Paul Hu777ed052023-06-19 13:35:15 +00001861 }
1862
1863 /**
1864 * @see MdnsUtils.Clock
1865 */
1866 public Clock makeClock() {
1867 return new Clock();
1868 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001869 }
1870
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001871 /**
1872 * Return whether a type is allowlisted to use the Java backend.
1873 * @param type The service type
1874 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1875 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1876 */
1877 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1878 @NonNull String flagPrefix) {
1879 if (type == null) return false;
1880 final String typesConfig = mDeps.getTypeAllowlistFlags();
1881 if (TextUtils.isEmpty(typesConfig)) return false;
1882
1883 final String mappingPrefix = type + ":";
1884 String mappedFlag = null;
1885 for (String mapping : TextUtils.split(typesConfig, ",")) {
1886 if (mapping.startsWith(mappingPrefix)) {
1887 mappedFlag = mapping.substring(mappingPrefix.length());
1888 break;
1889 }
1890 }
1891
1892 if (mappedFlag == null) return false;
1893
1894 return mDeps.isFeatureEnabled(mContext,
1895 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1896 }
1897
1898 private boolean useDiscoveryManagerForType(@Nullable String type) {
1899 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1900 }
1901
1902 private boolean useAdvertiserForType(@Nullable String type) {
1903 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1904 }
1905
paulhu1b35e822022-04-08 14:48:41 +08001906 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001907 HandlerThread thread = new HandlerThread(TAG);
1908 thread.start();
1909 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001910 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001911 return service;
1912 }
1913
paulhu2b9ed952022-02-10 21:58:32 +08001914 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1915 private final StateMachine mStateMachine;
1916
1917 MDnsEventCallback(StateMachine sm) {
1918 mStateMachine = sm;
1919 }
1920
1921 @Override
1922 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1923 mStateMachine.sendMessage(
1924 MDNS_SERVICE_EVENT, status.result, status.id, status);
1925 }
1926
1927 @Override
1928 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1929 mStateMachine.sendMessage(
1930 MDNS_SERVICE_EVENT, status.result, status.id, status);
1931 }
1932
1933 @Override
1934 public void onServiceResolutionStatus(final ResolutionInfo status) {
1935 mStateMachine.sendMessage(
1936 MDNS_SERVICE_EVENT, status.result, status.id, status);
1937 }
1938
1939 @Override
1940 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1941 mStateMachine.sendMessage(
1942 MDNS_SERVICE_EVENT, status.result, status.id, status);
1943 }
1944
1945 @Override
1946 public int getInterfaceVersion() throws RemoteException {
1947 return this.VERSION;
1948 }
1949
1950 @Override
1951 public String getInterfaceHash() throws RemoteException {
1952 return this.HASH;
1953 }
1954 }
1955
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001956 private void sendAllOffloadServiceInfos(@NonNull OffloadEngineInfo offloadEngineInfo) {
1957 final String targetInterface = offloadEngineInfo.mInterfaceName;
1958 final IOffloadEngine offloadEngine = offloadEngineInfo.mOffloadEngine;
1959 final List<MdnsAdvertiser.OffloadServiceInfoWrapper> offloadWrappers =
1960 mAdvertiser.getAllInterfaceOffloadServiceInfos(targetInterface);
1961 for (MdnsAdvertiser.OffloadServiceInfoWrapper wrapper : offloadWrappers) {
1962 try {
1963 offloadEngine.onOffloadServiceUpdated(wrapper.mOffloadServiceInfo);
1964 } catch (RemoteException e) {
1965 // Can happen in regular cases, do not log a stacktrace
1966 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
1967 }
1968 }
1969 }
1970
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001971 private void sendOffloadServiceInfosUpdate(@NonNull String targetInterfaceName,
1972 @NonNull OffloadServiceInfo offloadServiceInfo, boolean isRemove) {
1973 final int count = mOffloadEngines.beginBroadcast();
1974 try {
1975 for (int i = 0; i < count; i++) {
1976 final OffloadEngineInfo offloadEngineInfo =
1977 (OffloadEngineInfo) mOffloadEngines.getBroadcastCookie(i);
1978 final String interfaceName = offloadEngineInfo.mInterfaceName;
1979 if (!targetInterfaceName.equals(interfaceName)
1980 || ((offloadEngineInfo.mOffloadType
1981 & offloadServiceInfo.getOffloadType()) == 0)) {
1982 continue;
1983 }
1984 try {
1985 if (isRemove) {
1986 mOffloadEngines.getBroadcastItem(i).onOffloadServiceRemoved(
1987 offloadServiceInfo);
1988 } else {
1989 mOffloadEngines.getBroadcastItem(i).onOffloadServiceUpdated(
1990 offloadServiceInfo);
1991 }
1992 } catch (RemoteException e) {
1993 // Can happen in regular cases, do not log a stacktrace
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001994 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001995 }
1996 }
1997 } finally {
1998 mOffloadEngines.finishBroadcast();
1999 }
2000 }
2001
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002002 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002003 // TODO: add a callback to notify when a service is being added on each interface (as soon
2004 // as probing starts), and call mOffloadCallbacks. This callback is for
2005 // OFFLOAD_CAPABILITY_FILTER_REPLIES offload type.
2006
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002007 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00002008 public void onRegisterServiceSucceeded(int transactionId, NsdServiceInfo registeredInfo) {
2009 mServiceLogs.log("onRegisterServiceSucceeded: transactionId " + transactionId);
2010 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002011 if (clientInfo == null) return;
2012
Paul Hud44e1b72023-06-16 02:07:42 +00002013 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
2014 if (clientRequestId < 0) return;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002015
2016 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
2017 // historical behavior.
2018 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
Paul Hu777ed052023-06-19 13:35:15 +00002019 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu508a0122023-09-11 15:31:33 +08002020 clientInfo.onRegisterServiceSucceeded(clientRequestId, cbInfo, request);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002021 }
2022
2023 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00002024 public void onRegisterServiceFailed(int transactionId, int errorCode) {
2025 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002026 if (clientInfo == null) return;
2027
Paul Hud44e1b72023-06-16 02:07:42 +00002028 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
2029 if (clientRequestId < 0) return;
Paul Hu777ed052023-06-19 13:35:15 +00002030 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu508a0122023-09-11 15:31:33 +08002031 clientInfo.onRegisterServiceFailed(clientRequestId, errorCode, false /* isLegacy */,
2032 transactionId, request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002033 }
2034
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002035 @Override
2036 public void onOffloadStartOrUpdate(@NonNull String interfaceName,
2037 @NonNull OffloadServiceInfo offloadServiceInfo) {
2038 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, false /* isRemove */);
2039 }
2040
2041 @Override
2042 public void onOffloadStop(@NonNull String interfaceName,
2043 @NonNull OffloadServiceInfo offloadServiceInfo) {
2044 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, true /* isRemove */);
2045 }
2046
Paul Hud44e1b72023-06-16 02:07:42 +00002047 private ClientInfo getClientInfoOrLog(int transactionId) {
2048 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002049 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00002050 Log.e(TAG, String.format("Callback for service %d has no client", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002051 }
2052 return clientInfo;
2053 }
2054
Paul Hud44e1b72023-06-16 02:07:42 +00002055 private int getClientRequestIdOrLog(@NonNull ClientInfo info, int transactionId) {
2056 final int clientRequestId = info.getClientRequestId(transactionId);
2057 if (clientRequestId < 0) {
2058 Log.e(TAG, String.format(
2059 "Client request ID not found for service %d", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002060 }
Paul Hud44e1b72023-06-16 02:07:42 +00002061 return clientRequestId;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002062 }
2063 }
2064
Paul Hu2e0a88c2023-03-09 16:05:01 +08002065 private static class ConnectorArgs {
2066 @NonNull public final NsdServiceConnector connector;
2067 @NonNull public final INsdManagerCallback callback;
2068 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002069 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002070
2071 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00002072 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08002073 this.connector = connector;
2074 this.callback = callback;
2075 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002076 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002077 }
2078 }
2079
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002080 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08002081 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09002082 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu101dbf52023-08-09 16:05:20 +08002083 final int uid = mDeps.getCallingUid();
2084 if (cb == null) {
2085 throw new IllegalArgumentException("Unknown client callback from uid=" + uid);
2086 }
Paul Hu2e0a88c2023-03-09 16:05:01 +08002087 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002088 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00002089 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
Paul Hu101dbf52023-08-09 16:05:20 +08002090 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend, uid)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002091 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07002092 }
2093
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002094 private static class ListenerArgs {
2095 public final NsdServiceConnector connector;
2096 public final NsdServiceInfo serviceInfo;
2097 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
2098 this.connector = connector;
2099 this.serviceInfo = serviceInfo;
2100 }
2101 }
2102
Yuyang Huang86d083f2023-12-12 19:56:41 +09002103 private static class AdvertisingArgs {
2104 public final NsdServiceConnector connector;
2105 public final AdvertisingRequest advertisingRequest;
2106
2107 AdvertisingArgs(NsdServiceConnector connector, AdvertisingRequest advertisingRequest) {
2108 this.connector = connector;
2109 this.advertisingRequest = advertisingRequest;
2110 }
2111 }
2112
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002113 private class NsdServiceConnector extends INsdServiceConnector.Stub
2114 implements IBinder.DeathRecipient {
Yuyang Huang86d083f2023-12-12 19:56:41 +09002115
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002116 @Override
Yuyang Huang86d083f2023-12-12 19:56:41 +09002117 public void registerService(int listenerKey, AdvertisingRequest advertisingRequest)
2118 throws RemoteException {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002119 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2120 NsdManager.REGISTER_SERVICE, 0, listenerKey,
Yuyang Huang86d083f2023-12-12 19:56:41 +09002121 new AdvertisingArgs(this, advertisingRequest)
2122 ));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002123 }
2124
2125 @Override
2126 public void unregisterService(int listenerKey) {
2127 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2128 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
Yuyang Huang86d083f2023-12-12 19:56:41 +09002129 new ListenerArgs(this, (NsdServiceInfo) null)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002130 }
2131
2132 @Override
2133 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
2134 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2135 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
2136 new ListenerArgs(this, serviceInfo)));
2137 }
2138
2139 @Override
2140 public void stopDiscovery(int listenerKey) {
Yuyang Huang86d083f2023-12-12 19:56:41 +09002141 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.STOP_DISCOVERY,
2142 0, listenerKey, new ListenerArgs(this, (NsdServiceInfo) null)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002143 }
2144
2145 @Override
2146 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
2147 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2148 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
2149 new ListenerArgs(this, serviceInfo)));
2150 }
2151
2152 @Override
Paul Hub58deb72022-12-26 09:24:42 +00002153 public void stopResolution(int listenerKey) {
Yuyang Huang86d083f2023-12-12 19:56:41 +09002154 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.STOP_RESOLUTION,
2155 0, listenerKey, new ListenerArgs(this, (NsdServiceInfo) null)));
Paul Hub58deb72022-12-26 09:24:42 +00002156 }
2157
2158 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00002159 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
2160 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2161 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
2162 new ListenerArgs(this, serviceInfo)));
2163 }
2164
2165 @Override
2166 public void unregisterServiceInfoCallback(int listenerKey) {
2167 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2168 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
Yuyang Huang86d083f2023-12-12 19:56:41 +09002169 new ListenerArgs(this, (NsdServiceInfo) null)));
Paul Hu18aeccc2022-12-27 08:48:48 +00002170 }
2171
2172 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002173 public void startDaemon() {
Yuyang Huang86d083f2023-12-12 19:56:41 +09002174 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.DAEMON_STARTUP,
2175 new ListenerArgs(this, (NsdServiceInfo) null)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002176 }
2177
2178 @Override
2179 public void binderDied() {
2180 mNsdStateMachine.sendMessage(
2181 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002182
2183 }
2184
2185 @Override
2186 public void registerOffloadEngine(String ifaceName, IOffloadEngine cb,
2187 @OffloadEngine.OffloadCapability long offloadCapabilities,
2188 @OffloadEngine.OffloadType long offloadTypes) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002189 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002190 Objects.requireNonNull(ifaceName);
2191 Objects.requireNonNull(cb);
2192 mNsdStateMachine.sendMessage(
2193 mNsdStateMachine.obtainMessage(NsdManager.REGISTER_OFFLOAD_ENGINE,
2194 new OffloadEngineInfo(cb, ifaceName, offloadCapabilities,
2195 offloadTypes)));
2196 }
2197
2198 @Override
2199 public void unregisterOffloadEngine(IOffloadEngine cb) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002200 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002201 Objects.requireNonNull(cb);
2202 mNsdStateMachine.sendMessage(
2203 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_OFFLOAD_ENGINE, cb));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002204 }
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002205
2206 private static void checkOffloadEnginePermission(Context context) {
2207 if (!SdkLevel.isAtLeastT()) {
2208 throw new SecurityException("API is not available in before API level 33");
2209 }
Yuyang Huangd5896e72023-11-28 13:23:59 +09002210
Ken Chena7bae552023-12-27 11:40:57 +08002211 final ArrayList<String> permissionsList = new ArrayList<>(Arrays.asList(NETWORK_STACK,
2212 PERMISSION_MAINLINE_NETWORK_STACK, NETWORK_SETTINGS));
2213
2214 if (SdkLevel.isAtLeastV()) {
2215 // REGISTER_NSD_OFFLOAD_ENGINE was only added to the SDK in V.
2216 permissionsList.add(REGISTER_NSD_OFFLOAD_ENGINE);
2217 } else if (SdkLevel.isAtLeastU()) {
2218 // REGISTER_NSD_OFFLOAD_ENGINE cannot be backport to U. In U, check the DEVICE_POWER
2219 // permission instead.
2220 permissionsList.add(DEVICE_POWER);
Yuyang Huangd5896e72023-11-28 13:23:59 +09002221 }
2222
Ken Chena7bae552023-12-27 11:40:57 +08002223 if (PermissionUtils.checkAnyPermissionOf(context,
2224 permissionsList.toArray(new String[0]))) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002225 return;
2226 }
2227 throw new SecurityException("Requires one of the following permissions: "
Ken Chena7bae552023-12-27 11:40:57 +08002228 + String.join(", ", permissionsList) + ".");
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002229 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002230 }
2231
Hugo Benichi912db992017-04-24 16:41:03 +09002232 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07002233 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07002234 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09002235 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
2236 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07002237 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07002238 }
2239
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002240 private int getUniqueId() {
2241 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
2242 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002243 }
2244
Paul Hud44e1b72023-06-16 02:07:42 +00002245 private boolean registerService(int transactionId, NsdServiceInfo service) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002246 if (mMDnsManager == null) {
2247 Log.wtf(TAG, "registerService: mMDnsManager is null");
2248 return false;
2249 }
2250
Hugo Benichi6d706442017-04-24 16:19:58 +09002251 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002252 Log.d(TAG, "registerService: " + transactionId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002253 }
Hugo Benichi6d706442017-04-24 16:19:58 +09002254 String name = service.getServiceName();
2255 String type = service.getServiceType();
2256 int port = service.getPort();
2257 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002258 final int registerInterface = getNetworkInterfaceIndex(service);
2259 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08002260 Log.e(TAG, "Interface to register service on not found");
2261 return false;
2262 }
Paul Hud44e1b72023-06-16 02:07:42 +00002263 return mMDnsManager.registerService(
2264 transactionId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002265 }
2266
Paul Hud44e1b72023-06-16 02:07:42 +00002267 private boolean unregisterService(int transactionId) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002268 if (mMDnsManager == null) {
2269 Log.wtf(TAG, "unregisterService: mMDnsManager is null");
2270 return false;
2271 }
Paul Hud44e1b72023-06-16 02:07:42 +00002272 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002273 }
2274
Paul Hud44e1b72023-06-16 02:07:42 +00002275 private boolean discoverServices(int transactionId, NsdServiceInfo serviceInfo) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002276 if (mMDnsManager == null) {
2277 Log.wtf(TAG, "discoverServices: mMDnsManager is null");
2278 return false;
2279 }
2280
paulhu2b9ed952022-02-10 21:58:32 +08002281 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002282 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
2283 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002284 Log.e(TAG, "Interface to discover service on not found");
2285 return false;
2286 }
Paul Hud44e1b72023-06-16 02:07:42 +00002287 return mMDnsManager.discover(transactionId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002288 }
2289
Paul Hud44e1b72023-06-16 02:07:42 +00002290 private boolean stopServiceDiscovery(int transactionId) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002291 if (mMDnsManager == null) {
2292 Log.wtf(TAG, "stopServiceDiscovery: mMDnsManager is null");
2293 return false;
2294 }
Paul Hud44e1b72023-06-16 02:07:42 +00002295 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002296 }
2297
Paul Hud44e1b72023-06-16 02:07:42 +00002298 private boolean resolveService(int transactionId, NsdServiceInfo service) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002299 if (mMDnsManager == null) {
2300 Log.wtf(TAG, "resolveService: mMDnsManager is null");
2301 return false;
2302 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002303 final String name = service.getServiceName();
2304 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002305 final int resolveInterface = getNetworkInterfaceIndex(service);
2306 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002307 Log.e(TAG, "Interface to resolve service on not found");
2308 return false;
2309 }
Paul Hud44e1b72023-06-16 02:07:42 +00002310 return mMDnsManager.resolve(transactionId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002311 }
2312
2313 /**
2314 * Guess the interface to use to resolve or discover a service on a specific network.
2315 *
2316 * This is an imperfect guess, as for example the network may be gone or not yet fully
2317 * registered. This is fine as failing is correct if the network is gone, and a client
2318 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
2319 * this is to support the legacy mdnsresponder implementation, which historically resolved
2320 * services on an unspecified network.
2321 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002322 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
2323 final Network network = serviceInfo.getNetwork();
2324 if (network == null) {
2325 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
2326 // provided by NsdService from discovery results, and the service was found on an
2327 // interface that has no app-usable Network).
2328 if (serviceInfo.getInterfaceIndex() != 0) {
2329 return serviceInfo.getInterfaceIndex();
2330 }
2331 return IFACE_IDX_ANY;
2332 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002333
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002334 String interfaceName = getNetworkInterfaceName(network);
2335 if (interfaceName == null) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002336 return IFACE_IDX_ANY;
2337 }
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002338 return getNetworkInterfaceIndexByName(interfaceName);
2339 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002340
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002341 private String getNetworkInterfaceName(@Nullable Network network) {
2342 if (network == null) {
2343 return null;
2344 }
2345 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
2346 if (cm == null) {
2347 Log.wtf(TAG, "No ConnectivityManager");
2348 return null;
2349 }
2350 final LinkProperties lp = cm.getLinkProperties(network);
2351 if (lp == null) {
2352 return null;
2353 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002354 // Only resolve on non-stacked interfaces
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002355 return lp.getInterfaceName();
2356 }
2357
2358 private int getNetworkInterfaceIndexByName(final String ifaceName) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002359 final NetworkInterface iface;
2360 try {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002361 iface = NetworkInterface.getByName(ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002362 } catch (SocketException e) {
2363 Log.e(TAG, "Error querying interface", e);
2364 return IFACE_IDX_ANY;
2365 }
2366
2367 if (iface == null) {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002368 Log.e(TAG, "Interface not found: " + ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002369 return IFACE_IDX_ANY;
2370 }
2371
2372 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002373 }
2374
Paul Hud44e1b72023-06-16 02:07:42 +00002375 private boolean stopResolveService(int transactionId) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002376 if (mMDnsManager == null) {
2377 Log.wtf(TAG, "stopResolveService: mMDnsManager is null");
2378 return false;
2379 }
Paul Hud44e1b72023-06-16 02:07:42 +00002380 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002381 }
2382
Paul Hud44e1b72023-06-16 02:07:42 +00002383 private boolean getAddrInfo(int transactionId, String hostname, int interfaceIdx) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002384 if (mMDnsManager == null) {
2385 Log.wtf(TAG, "getAddrInfo: mMDnsManager is null");
2386 return false;
2387 }
Paul Hud44e1b72023-06-16 02:07:42 +00002388 return mMDnsManager.getServiceAddress(transactionId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002389 }
2390
Paul Hud44e1b72023-06-16 02:07:42 +00002391 private boolean stopGetAddrInfo(int transactionId) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002392 if (mMDnsManager == null) {
2393 Log.wtf(TAG, "stopGetAddrInfo: mMDnsManager is null");
2394 return false;
2395 }
Paul Hud44e1b72023-06-16 02:07:42 +00002396 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002397 }
2398
2399 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00002400 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2401 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002402
Paul Hub2e67d32023-04-18 05:50:14 +00002403 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2404 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07002405 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00002406
2407 // Dump service and clients logs
2408 pw.println();
Paul Hu14667de2023-04-17 22:42:47 +08002409 pw.println("Logs:");
Paul Hub2e67d32023-04-18 05:50:14 +00002410 pw.increaseIndent();
2411 mServiceLogs.reverseDump(pw);
2412 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002413 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002414
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002415 private abstract static class ClientRequest {
Paul Hud44e1b72023-06-16 02:07:42 +00002416 private final int mTransactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002417 private final long mStartTimeMs;
Paul Hu812e9212023-06-20 06:24:53 +00002418 private int mFoundServiceCount = 0;
2419 private int mLostServiceCount = 0;
2420 private final Set<String> mServices = new ArraySet<>();
Paul Hua6bc4632023-06-26 01:18:29 +00002421 private boolean mIsServiceFromCache = false;
Paul Hubad6fe92023-07-24 21:25:22 +08002422 private int mSentQueryCount = NO_SENT_QUERY_COUNT;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002423
Paul Hu812e9212023-06-20 06:24:53 +00002424 private ClientRequest(int transactionId, long startTimeMs) {
Paul Hud44e1b72023-06-16 02:07:42 +00002425 mTransactionId = transactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002426 mStartTimeMs = startTimeMs;
2427 }
2428
Paul Hu812e9212023-06-20 06:24:53 +00002429 public long calculateRequestDurationMs(long stopTimeMs) {
Paul Hu777ed052023-06-19 13:35:15 +00002430 return stopTimeMs - mStartTimeMs;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002431 }
Paul Hu812e9212023-06-20 06:24:53 +00002432
2433 public void onServiceFound(String serviceName) {
2434 mFoundServiceCount++;
2435 if (mServices.size() <= MAX_SERVICES_COUNT_METRIC_PER_CLIENT) {
2436 mServices.add(serviceName);
2437 }
2438 }
2439
2440 public void onServiceLost() {
2441 mLostServiceCount++;
2442 }
2443
2444 public int getFoundServiceCount() {
2445 return mFoundServiceCount;
2446 }
2447
2448 public int getLostServiceCount() {
2449 return mLostServiceCount;
2450 }
2451
2452 public int getServicesCount() {
2453 return mServices.size();
2454 }
Paul Hua6bc4632023-06-26 01:18:29 +00002455
2456 public void setServiceFromCache(boolean isServiceFromCache) {
2457 mIsServiceFromCache = isServiceFromCache;
2458 }
2459
2460 public boolean isServiceFromCache() {
2461 return mIsServiceFromCache;
2462 }
Paul Hubad6fe92023-07-24 21:25:22 +08002463
2464 public void onQuerySent() {
2465 mSentQueryCount++;
2466 }
2467
2468 public int getSentQueryCount() {
2469 return mSentQueryCount;
2470 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002471 }
2472
2473 private static class LegacyClientRequest extends ClientRequest {
2474 private final int mRequestCode;
2475
Paul Hu812e9212023-06-20 06:24:53 +00002476 private LegacyClientRequest(int transactionId, int requestCode, long startTimeMs) {
2477 super(transactionId, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002478 mRequestCode = requestCode;
2479 }
2480 }
2481
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002482 private abstract static class JavaBackendClientRequest extends ClientRequest {
2483 @Nullable
2484 private final Network mRequestedNetwork;
2485
Paul Hu777ed052023-06-19 13:35:15 +00002486 private JavaBackendClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002487 long startTimeMs) {
2488 super(transactionId, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002489 mRequestedNetwork = requestedNetwork;
2490 }
2491
2492 @Nullable
2493 public Network getRequestedNetwork() {
2494 return mRequestedNetwork;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002495 }
2496 }
2497
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002498 private static class AdvertiserClientRequest extends JavaBackendClientRequest {
Paul Hu777ed052023-06-19 13:35:15 +00002499 private AdvertiserClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002500 long startTimeMs) {
2501 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002502 }
2503 }
2504
2505 private static class DiscoveryManagerRequest extends JavaBackendClientRequest {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002506 @NonNull
2507 private final MdnsListener mListener;
2508
Paul Hud44e1b72023-06-16 02:07:42 +00002509 private DiscoveryManagerRequest(int transactionId, @NonNull MdnsListener listener,
Paul Hu812e9212023-06-20 06:24:53 +00002510 @Nullable Network requestedNetwork, long startTimeMs) {
2511 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002512 mListener = listener;
2513 }
2514 }
2515
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002516 /* Information tracked per client */
2517 private class ClientInfo {
2518
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002519 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002520 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002521 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002522 private NsdServiceInfo mResolvedService;
2523
Paul Hud44e1b72023-06-16 02:07:42 +00002524 /* A map from client request ID (listenerKey) to the request */
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002525 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08002526
Luke Huangf7277ed2021-07-12 21:15:10 +08002527 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002528 private boolean mIsPreSClient = false;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002529 private final int mUid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002530 // The flag of using java backend if the client's target SDK >= U
2531 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002532 // Store client logs
2533 private final SharedLog mClientLogs;
Paul Hucdef3532023-06-18 14:47:35 +00002534 // Report the nsd metrics data
2535 private final NetworkNsdReportedMetrics mMetrics;
Luke Huangf7277ed2021-07-12 21:15:10 +08002536
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002537 private ClientInfo(INsdManagerCallback cb, int uid, boolean useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +00002538 SharedLog sharedLog, NetworkNsdReportedMetrics metrics) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002539 mCb = cb;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002540 mUid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002541 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002542 mClientLogs = sharedLog;
2543 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Paul Hucdef3532023-06-18 14:47:35 +00002544 mMetrics = metrics;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002545 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002546
2547 @Override
2548 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06002549 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07002550 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002551 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002552 sb.append("mUseJavaBackend ").append(mUseJavaBackend).append("\n");
2553 sb.append("mUid ").append(mUid).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002554 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002555 int clientRequestId = mClientRequests.keyAt(i);
2556 sb.append("clientRequestId ")
2557 .append(clientRequestId)
2558 .append(" transactionId ").append(mClientRequests.valueAt(i).mTransactionId)
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002559 .append(" type ").append(
2560 mClientRequests.valueAt(i).getClass().getSimpleName())
2561 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07002562 }
2563 return sb.toString();
2564 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002565
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002566 private boolean isPreSClient() {
2567 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08002568 }
2569
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002570 private void setPreSClient() {
2571 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08002572 }
2573
Paul Hu812e9212023-06-20 06:24:53 +00002574 private MdnsListener unregisterMdnsListenerFromRequest(ClientRequest request) {
Paul Hue4f5f252023-02-16 21:13:47 +08002575 final MdnsListener listener =
2576 ((DiscoveryManagerRequest) request).mListener;
2577 mMdnsDiscoveryManager.unregisterListener(
2578 listener.getListenedServiceType(), listener);
Paul Hu812e9212023-06-20 06:24:53 +00002579 return listener;
Paul Hue4f5f252023-02-16 21:13:47 +08002580 }
2581
Dave Plattfeff2af2014-03-07 14:48:22 -08002582 // Remove any pending requests from the global map when we get rid of a client,
2583 // and send cancellations to the daemon.
2584 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00002585 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09002586 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002587 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002588 final int clientRequestId = mClientRequests.keyAt(i);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002589 final ClientRequest request = mClientRequests.valueAt(i);
Paul Hud44e1b72023-06-16 02:07:42 +00002590 final int transactionId = request.mTransactionId;
2591 mTransactionIdToClientInfoMap.remove(transactionId);
paulhub2225702021-11-17 09:35:33 +08002592 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002593 Log.d(TAG, "Terminating clientRequestId " + clientRequestId
2594 + " transactionId " + transactionId
2595 + " type " + mClientRequests.get(clientRequestId));
paulhub2225702021-11-17 09:35:33 +08002596 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002597
2598 if (request instanceof DiscoveryManagerRequest) {
Paul Hu812e9212023-06-20 06:24:53 +00002599 final MdnsListener listener = unregisterMdnsListenerFromRequest(request);
2600 if (listener instanceof DiscoveryListener) {
Paul Hu508a0122023-09-11 15:31:33 +08002601 mMetrics.reportServiceDiscoveryStop(false /* isLegacy */, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00002602 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2603 request.getFoundServiceCount(),
2604 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002605 request.getServicesCount(),
2606 request.getSentQueryCount());
Paul Hu60149052023-07-31 14:26:08 +08002607 } else if (listener instanceof ResolutionListener) {
Paul Hu508a0122023-09-11 15:31:33 +08002608 mMetrics.reportServiceResolutionStop(false /* isLegacy */, transactionId,
Paul Hu60149052023-07-31 14:26:08 +08002609 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Huddce5912023-08-01 10:26:49 +08002610 } else if (listener instanceof ServiceInfoListener) {
2611 mMetrics.reportServiceInfoCallbackUnregistered(transactionId,
2612 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2613 request.getFoundServiceCount(),
2614 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002615 request.isServiceFromCache(),
2616 request.getSentQueryCount());
Paul Hu812e9212023-06-20 06:24:53 +00002617 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002618 continue;
2619 }
2620
2621 if (request instanceof AdvertiserClientRequest) {
Paul Hu043bcd42023-07-14 16:38:25 +08002622 final AdvertiserMetrics metrics =
2623 mAdvertiser.getAdvertiserMetrics(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00002624 mAdvertiser.removeService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002625 mMetrics.reportServiceUnregistration(false /* isLegacy */, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002626 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2627 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2628 metrics.mConflictDuringProbingCount,
2629 metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002630 continue;
2631 }
2632
2633 if (!(request instanceof LegacyClientRequest)) {
2634 throw new IllegalStateException("Unknown request type: " + request.getClass());
2635 }
2636
2637 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08002638 case NsdManager.DISCOVER_SERVICES:
Paul Hud44e1b72023-06-16 02:07:42 +00002639 stopServiceDiscovery(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002640 mMetrics.reportServiceDiscoveryStop(true /* isLegacy */, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00002641 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2642 request.getFoundServiceCount(),
2643 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002644 request.getServicesCount(),
2645 NO_SENT_QUERY_COUNT);
Dave Plattfeff2af2014-03-07 14:48:22 -08002646 break;
2647 case NsdManager.RESOLVE_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002648 stopResolveService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002649 mMetrics.reportServiceResolutionStop(true /* isLegacy */, transactionId,
Paul Hu60149052023-07-31 14:26:08 +08002650 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Dave Plattfeff2af2014-03-07 14:48:22 -08002651 break;
2652 case NsdManager.REGISTER_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002653 unregisterService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002654 mMetrics.reportServiceUnregistration(true /* isLegacy */, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002655 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2656 NO_PACKET /* repliedRequestsCount */,
2657 NO_PACKET /* sentPacketCount */,
2658 0 /* conflictDuringProbingCount */,
2659 0 /* conflictAfterProbingCount */);
Dave Plattfeff2af2014-03-07 14:48:22 -08002660 break;
2661 default:
2662 break;
2663 }
2664 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002665 mClientRequests.clear();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002666 updateMulticastLock();
2667 }
2668
2669 /**
2670 * Returns true if this client has any Java backend request that requests one of the given
2671 * networks.
2672 */
2673 boolean hasAnyJavaBackendRequestForNetworks(@NonNull ArraySet<Network> networks) {
2674 for (int i = 0; i < mClientRequests.size(); i++) {
2675 final ClientRequest req = mClientRequests.valueAt(i);
2676 if (!(req instanceof JavaBackendClientRequest)) {
2677 continue;
2678 }
2679 final Network reqNetwork = ((JavaBackendClientRequest) mClientRequests.valueAt(i))
2680 .getRequestedNetwork();
2681 if (MdnsUtils.isAnyNetworkMatched(reqNetwork, networks)) {
2682 return true;
2683 }
2684 }
2685 return false;
Dave Plattfeff2af2014-03-07 14:48:22 -08002686 }
2687
Paul Hud44e1b72023-06-16 02:07:42 +00002688 // mClientRequests is a sparse array of client request id -> ClientRequest. For a given
2689 // transaction id, return the corresponding client request id.
2690 private int getClientRequestId(final int transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002691 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002692 if (mClientRequests.valueAt(i).mTransactionId == transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002693 return mClientRequests.keyAt(i);
2694 }
Christopher Lane74411222014-04-25 18:39:07 -07002695 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002696 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07002697 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002698
Paul Hub2e67d32023-04-18 05:50:14 +00002699 private void log(String message) {
2700 mClientLogs.log(message);
2701 }
2702
Paul Hu508a0122023-09-11 15:31:33 +08002703 private static boolean isLegacyClientRequest(@NonNull ClientRequest request) {
2704 return !(request instanceof DiscoveryManagerRequest)
2705 && !(request instanceof AdvertiserClientRequest);
2706 }
2707
2708 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info,
2709 ClientRequest request) {
2710 mMetrics.reportServiceDiscoveryStarted(
2711 isLegacyClientRequest(request), request.mTransactionId);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002712 try {
2713 mCb.onDiscoverServicesStarted(listenerKey, info);
2714 } catch (RemoteException e) {
2715 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
2716 }
2717 }
Paul Hu508a0122023-09-11 15:31:33 +08002718 void onDiscoverServicesFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2719 onDiscoverServicesFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2720 0L /* durationMs */);
Paul Hu812e9212023-06-20 06:24:53 +00002721 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002722
Paul Hu508a0122023-09-11 15:31:33 +08002723 void onDiscoverServicesFailed(int listenerKey, int error, boolean isLegacy,
2724 int transactionId, long durationMs) {
2725 mMetrics.reportServiceDiscoveryFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002726 try {
2727 mCb.onDiscoverServicesFailed(listenerKey, error);
2728 } catch (RemoteException e) {
2729 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
2730 }
2731 }
2732
Paul Hu812e9212023-06-20 06:24:53 +00002733 void onServiceFound(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2734 request.onServiceFound(info.getServiceName());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002735 try {
2736 mCb.onServiceFound(listenerKey, info);
2737 } catch (RemoteException e) {
2738 Log.e(TAG, "Error calling onServiceFound(", e);
2739 }
2740 }
2741
Paul Hu812e9212023-06-20 06:24:53 +00002742 void onServiceLost(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2743 request.onServiceLost();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002744 try {
2745 mCb.onServiceLost(listenerKey, info);
2746 } catch (RemoteException e) {
2747 Log.e(TAG, "Error calling onServiceLost(", e);
2748 }
2749 }
2750
2751 void onStopDiscoveryFailed(int listenerKey, int error) {
2752 try {
2753 mCb.onStopDiscoveryFailed(listenerKey, error);
2754 } catch (RemoteException e) {
2755 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
2756 }
2757 }
2758
Paul Hu812e9212023-06-20 06:24:53 +00002759 void onStopDiscoverySucceeded(int listenerKey, ClientRequest request) {
2760 mMetrics.reportServiceDiscoveryStop(
Paul Hu508a0122023-09-11 15:31:33 +08002761 isLegacyClientRequest(request),
Paul Hu812e9212023-06-20 06:24:53 +00002762 request.mTransactionId,
2763 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2764 request.getFoundServiceCount(),
2765 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002766 request.getServicesCount(),
2767 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002768 try {
2769 mCb.onStopDiscoverySucceeded(listenerKey);
2770 } catch (RemoteException e) {
2771 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2772 }
2773 }
2774
Paul Hu508a0122023-09-11 15:31:33 +08002775 void onRegisterServiceFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2776 onRegisterServiceFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2777 0L /* durationMs */);
Paul Hu777ed052023-06-19 13:35:15 +00002778 }
2779
Paul Hu508a0122023-09-11 15:31:33 +08002780 void onRegisterServiceFailed(int listenerKey, int error, boolean isLegacy,
2781 int transactionId, long durationMs) {
2782 mMetrics.reportServiceRegistrationFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002783 try {
2784 mCb.onRegisterServiceFailed(listenerKey, error);
2785 } catch (RemoteException e) {
2786 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2787 }
2788 }
2789
Paul Hu508a0122023-09-11 15:31:33 +08002790 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info,
2791 ClientRequest request) {
2792 mMetrics.reportServiceRegistrationSucceeded(isLegacyClientRequest(request),
2793 request.mTransactionId,
2794 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002795 try {
2796 mCb.onRegisterServiceSucceeded(listenerKey, info);
2797 } catch (RemoteException e) {
2798 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2799 }
2800 }
2801
2802 void onUnregisterServiceFailed(int listenerKey, int error) {
2803 try {
2804 mCb.onUnregisterServiceFailed(listenerKey, error);
2805 } catch (RemoteException e) {
2806 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2807 }
2808 }
2809
Paul Hu508a0122023-09-11 15:31:33 +08002810 void onUnregisterServiceSucceeded(int listenerKey, ClientRequest request,
Paul Hu043bcd42023-07-14 16:38:25 +08002811 AdvertiserMetrics metrics) {
Paul Hu508a0122023-09-11 15:31:33 +08002812 mMetrics.reportServiceUnregistration(isLegacyClientRequest(request),
2813 request.mTransactionId,
2814 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hu043bcd42023-07-14 16:38:25 +08002815 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2816 metrics.mConflictDuringProbingCount, metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002817 try {
2818 mCb.onUnregisterServiceSucceeded(listenerKey);
2819 } catch (RemoteException e) {
2820 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2821 }
2822 }
2823
Paul Hu508a0122023-09-11 15:31:33 +08002824 void onResolveServiceFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2825 onResolveServiceFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2826 0L /* durationMs */);
Paul Hua6bc4632023-06-26 01:18:29 +00002827 }
2828
Paul Hu508a0122023-09-11 15:31:33 +08002829 void onResolveServiceFailed(int listenerKey, int error, boolean isLegacy,
2830 int transactionId, long durationMs) {
2831 mMetrics.reportServiceResolutionFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002832 try {
2833 mCb.onResolveServiceFailed(listenerKey, error);
2834 } catch (RemoteException e) {
2835 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2836 }
2837 }
2838
Paul Hua6bc4632023-06-26 01:18:29 +00002839 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info,
2840 ClientRequest request) {
2841 mMetrics.reportServiceResolved(
Paul Hu508a0122023-09-11 15:31:33 +08002842 isLegacyClientRequest(request),
Paul Hua6bc4632023-06-26 01:18:29 +00002843 request.mTransactionId,
2844 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hubad6fe92023-07-24 21:25:22 +08002845 request.isServiceFromCache(),
2846 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002847 try {
2848 mCb.onResolveServiceSucceeded(listenerKey, info);
2849 } catch (RemoteException e) {
2850 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2851 }
2852 }
Paul Hub58deb72022-12-26 09:24:42 +00002853
2854 void onStopResolutionFailed(int listenerKey, int error) {
2855 try {
2856 mCb.onStopResolutionFailed(listenerKey, error);
2857 } catch (RemoteException e) {
2858 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2859 }
2860 }
2861
Paul Hu60149052023-07-31 14:26:08 +08002862 void onStopResolutionSucceeded(int listenerKey, ClientRequest request) {
2863 mMetrics.reportServiceResolutionStop(
Paul Hu508a0122023-09-11 15:31:33 +08002864 isLegacyClientRequest(request),
Paul Hu60149052023-07-31 14:26:08 +08002865 request.mTransactionId,
2866 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hub58deb72022-12-26 09:24:42 +00002867 try {
2868 mCb.onStopResolutionSucceeded(listenerKey);
2869 } catch (RemoteException e) {
2870 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2871 }
2872 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002873
2874 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
Paul Huddce5912023-08-01 10:26:49 +08002875 mMetrics.reportServiceInfoCallbackRegistrationFailed(NO_TRANSACTION);
Paul Hu18aeccc2022-12-27 08:48:48 +00002876 try {
2877 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2878 } catch (RemoteException e) {
2879 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2880 }
2881 }
2882
Paul Huddce5912023-08-01 10:26:49 +08002883 void onServiceInfoCallbackRegistered(int transactionId) {
2884 mMetrics.reportServiceInfoCallbackRegistered(transactionId);
2885 }
2886
2887 void onServiceUpdated(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2888 request.onServiceFound(info.getServiceName());
Paul Hu18aeccc2022-12-27 08:48:48 +00002889 try {
2890 mCb.onServiceUpdated(listenerKey, info);
2891 } catch (RemoteException e) {
2892 Log.e(TAG, "Error calling onServiceUpdated", e);
2893 }
2894 }
2895
Paul Huddce5912023-08-01 10:26:49 +08002896 void onServiceUpdatedLost(int listenerKey, ClientRequest request) {
2897 request.onServiceLost();
Paul Hu18aeccc2022-12-27 08:48:48 +00002898 try {
2899 mCb.onServiceUpdatedLost(listenerKey);
2900 } catch (RemoteException e) {
2901 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2902 }
2903 }
2904
Paul Huddce5912023-08-01 10:26:49 +08002905 void onServiceInfoCallbackUnregistered(int listenerKey, ClientRequest request) {
2906 mMetrics.reportServiceInfoCallbackUnregistered(
2907 request.mTransactionId,
2908 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2909 request.getFoundServiceCount(),
2910 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002911 request.isServiceFromCache(),
2912 request.getSentQueryCount());
Paul Hu18aeccc2022-12-27 08:48:48 +00002913 try {
2914 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2915 } catch (RemoteException e) {
2916 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2917 }
2918 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002919 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002920}