blob: 62a2ae5230f1eb92d9edf71d4bb6f67460862e5a [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
Remi NGUYEN VAN0ca094b2023-09-13 16:27:12 +0900179 private static final String FORCE_ENABLE_FLAG_FOR_TEST_PREFIX = "test_";
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))
Remi NGUYEN VAN0ca094b2023-09-13 16:27:12 +09001742 .setIsUnicastReplyEnabled(mDeps.isFeatureEnabled(
1743 mContext, MdnsFeatureFlags.NSD_UNICAST_REPLY_ENABLED))
1744 .setOverrideProvider(flag -> mDeps.isFeatureEnabled(
1745 mContext, FORCE_ENABLE_FLAG_FOR_TEST_PREFIX + flag))
Paul Huf3fe3332023-10-16 17:13:25 +08001746 .build();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001747 mMdnsSocketClient =
Yuyang Huang7ddf2932023-08-01 18:16:30 +09001748 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider,
Paul Hufd357ef2023-11-01 16:32:45 +08001749 LOGGER.forSubComponent("MdnsMultinetworkSocketClient"), flags);
Paul Hu14667de2023-04-17 22:42:47 +08001750 mMdnsDiscoveryManager = deps.makeMdnsDiscoveryManager(new ExecutorProvider(),
Paul Huf3fe3332023-10-16 17:13:25 +08001751 mMdnsSocketClient, LOGGER.forSubComponent("MdnsDiscoveryManager"), flags);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001752 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1753 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
Remi NGUYEN VAN5c9d6cb2024-01-23 17:14:55 +09001754 new AdvertiserCallback(), LOGGER.forSubComponent("MdnsAdvertiser"), flags,
1755 mContext);
Paul Hu777ed052023-06-19 13:35:15 +00001756 mClock = deps.makeClock();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001757 }
1758
1759 /**
1760 * Dependencies of NsdService, for injection in tests.
1761 */
1762 @VisibleForTesting
1763 public static class Dependencies {
1764 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001765 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001766 *
1767 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001768 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001769 */
1770 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001771 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001772 MDNS_DISCOVERY_MANAGER_VERSION);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001773 }
1774
1775 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001776 * Check whether the MdnsAdvertiser feature is enabled.
1777 *
1778 * @param context The global context information about an app environment.
1779 * @return true if the MdnsAdvertiser feature is enabled.
1780 */
1781 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001782 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001783 MDNS_ADVERTISER_VERSION);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001784 }
1785
1786 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001787 * Get the type allowlist flag value.
1788 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1789 */
1790 @Nullable
1791 public String getTypeAllowlistFlags() {
1792 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1793 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1794 }
1795
1796 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001797 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001798 */
1799 public boolean isFeatureEnabled(Context context, String feature) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001800 return DeviceConfigUtils.isTetheringFeatureEnabled(context, feature);
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001801 }
1802
1803 /**
Yuyang Huangb96a0712023-09-07 15:13:15 +09001804 * @see DeviceConfigUtils#isTetheringFeatureNotChickenedOut
1805 */
Motomu Utsumied4e7ec2023-09-13 14:58:32 +09001806 public boolean isTetheringFeatureNotChickenedOut(Context context, String feature) {
1807 return DeviceConfigUtils.isTetheringFeatureNotChickenedOut(context, feature);
Yuyang Huangb96a0712023-09-07 15:13:15 +09001808 }
1809
1810 /**
Paul Huf3fe3332023-10-16 17:13:25 +08001811 * @see DeviceConfigUtils#isTrunkStableFeatureEnabled
1812 */
1813 public boolean isTrunkStableFeatureEnabled(String feature) {
1814 return DeviceConfigUtils.isTrunkStableFeatureEnabled(feature);
1815 }
1816
1817 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001818 * @see MdnsDiscoveryManager
1819 */
1820 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
Paul Hu14667de2023-04-17 22:42:47 +08001821 @NonNull ExecutorProvider executorProvider,
Paul Huf3fe3332023-10-16 17:13:25 +08001822 @NonNull MdnsMultinetworkSocketClient socketClient, @NonNull SharedLog sharedLog,
1823 @NonNull MdnsFeatureFlags featureFlags) {
1824 return new MdnsDiscoveryManager(
1825 executorProvider, socketClient, sharedLog, featureFlags);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001826 }
1827
1828 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001829 * @see MdnsAdvertiser
1830 */
1831 public MdnsAdvertiser makeMdnsAdvertiser(
1832 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
Yuyang Huangb96a0712023-09-07 15:13:15 +09001833 @NonNull MdnsAdvertiser.AdvertiserCallback cb, @NonNull SharedLog sharedLog,
Remi NGUYEN VAN5c9d6cb2024-01-23 17:14:55 +09001834 MdnsFeatureFlags featureFlags, Context context) {
1835 return new MdnsAdvertiser(looper, socketProvider, cb, sharedLog, featureFlags, context);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001836 }
1837
1838 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001839 * @see MdnsSocketProvider
1840 */
Paul Hu14667de2023-04-17 22:42:47 +08001841 public MdnsSocketProvider makeMdnsSocketProvider(@NonNull Context context,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001842 @NonNull Looper looper, @NonNull SharedLog sharedLog,
1843 @NonNull MdnsSocketProvider.SocketRequestMonitor socketCreationCallback) {
1844 return new MdnsSocketProvider(context, looper, sharedLog, socketCreationCallback);
1845 }
1846
1847 /**
1848 * @see DeviceConfig#getInt(String, String, int)
1849 */
1850 public int getDeviceConfigInt(@NonNull String config, int defaultValue) {
1851 return DeviceConfig.getInt(NAMESPACE_TETHERING, config, defaultValue);
1852 }
1853
1854 /**
1855 * @see Binder#getCallingUid()
1856 */
1857 public int getCallingUid() {
1858 return Binder.getCallingUid();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001859 }
Paul Hu777ed052023-06-19 13:35:15 +00001860
1861 /**
1862 * @see NetworkNsdReportedMetrics
1863 */
Paul Hu508a0122023-09-11 15:31:33 +08001864 public NetworkNsdReportedMetrics makeNetworkNsdReportedMetrics(int clientId) {
1865 return new NetworkNsdReportedMetrics(clientId);
Paul Hu777ed052023-06-19 13:35:15 +00001866 }
1867
1868 /**
1869 * @see MdnsUtils.Clock
1870 */
1871 public Clock makeClock() {
1872 return new Clock();
1873 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001874 }
1875
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001876 /**
1877 * Return whether a type is allowlisted to use the Java backend.
1878 * @param type The service type
1879 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1880 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1881 */
1882 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1883 @NonNull String flagPrefix) {
1884 if (type == null) return false;
1885 final String typesConfig = mDeps.getTypeAllowlistFlags();
1886 if (TextUtils.isEmpty(typesConfig)) return false;
1887
1888 final String mappingPrefix = type + ":";
1889 String mappedFlag = null;
1890 for (String mapping : TextUtils.split(typesConfig, ",")) {
1891 if (mapping.startsWith(mappingPrefix)) {
1892 mappedFlag = mapping.substring(mappingPrefix.length());
1893 break;
1894 }
1895 }
1896
1897 if (mappedFlag == null) return false;
1898
1899 return mDeps.isFeatureEnabled(mContext,
1900 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1901 }
1902
1903 private boolean useDiscoveryManagerForType(@Nullable String type) {
1904 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1905 }
1906
1907 private boolean useAdvertiserForType(@Nullable String type) {
1908 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1909 }
1910
paulhu1b35e822022-04-08 14:48:41 +08001911 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001912 HandlerThread thread = new HandlerThread(TAG);
1913 thread.start();
1914 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001915 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001916 return service;
1917 }
1918
paulhu2b9ed952022-02-10 21:58:32 +08001919 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1920 private final StateMachine mStateMachine;
1921
1922 MDnsEventCallback(StateMachine sm) {
1923 mStateMachine = sm;
1924 }
1925
1926 @Override
1927 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1928 mStateMachine.sendMessage(
1929 MDNS_SERVICE_EVENT, status.result, status.id, status);
1930 }
1931
1932 @Override
1933 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1934 mStateMachine.sendMessage(
1935 MDNS_SERVICE_EVENT, status.result, status.id, status);
1936 }
1937
1938 @Override
1939 public void onServiceResolutionStatus(final ResolutionInfo status) {
1940 mStateMachine.sendMessage(
1941 MDNS_SERVICE_EVENT, status.result, status.id, status);
1942 }
1943
1944 @Override
1945 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1946 mStateMachine.sendMessage(
1947 MDNS_SERVICE_EVENT, status.result, status.id, status);
1948 }
1949
1950 @Override
1951 public int getInterfaceVersion() throws RemoteException {
1952 return this.VERSION;
1953 }
1954
1955 @Override
1956 public String getInterfaceHash() throws RemoteException {
1957 return this.HASH;
1958 }
1959 }
1960
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001961 private void sendAllOffloadServiceInfos(@NonNull OffloadEngineInfo offloadEngineInfo) {
1962 final String targetInterface = offloadEngineInfo.mInterfaceName;
1963 final IOffloadEngine offloadEngine = offloadEngineInfo.mOffloadEngine;
1964 final List<MdnsAdvertiser.OffloadServiceInfoWrapper> offloadWrappers =
1965 mAdvertiser.getAllInterfaceOffloadServiceInfos(targetInterface);
1966 for (MdnsAdvertiser.OffloadServiceInfoWrapper wrapper : offloadWrappers) {
1967 try {
1968 offloadEngine.onOffloadServiceUpdated(wrapper.mOffloadServiceInfo);
1969 } catch (RemoteException e) {
1970 // Can happen in regular cases, do not log a stacktrace
1971 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
1972 }
1973 }
1974 }
1975
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001976 private void sendOffloadServiceInfosUpdate(@NonNull String targetInterfaceName,
1977 @NonNull OffloadServiceInfo offloadServiceInfo, boolean isRemove) {
1978 final int count = mOffloadEngines.beginBroadcast();
1979 try {
1980 for (int i = 0; i < count; i++) {
1981 final OffloadEngineInfo offloadEngineInfo =
1982 (OffloadEngineInfo) mOffloadEngines.getBroadcastCookie(i);
1983 final String interfaceName = offloadEngineInfo.mInterfaceName;
1984 if (!targetInterfaceName.equals(interfaceName)
1985 || ((offloadEngineInfo.mOffloadType
1986 & offloadServiceInfo.getOffloadType()) == 0)) {
1987 continue;
1988 }
1989 try {
1990 if (isRemove) {
1991 mOffloadEngines.getBroadcastItem(i).onOffloadServiceRemoved(
1992 offloadServiceInfo);
1993 } else {
1994 mOffloadEngines.getBroadcastItem(i).onOffloadServiceUpdated(
1995 offloadServiceInfo);
1996 }
1997 } catch (RemoteException e) {
1998 // Can happen in regular cases, do not log a stacktrace
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001999 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002000 }
2001 }
2002 } finally {
2003 mOffloadEngines.finishBroadcast();
2004 }
2005 }
2006
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002007 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002008 // TODO: add a callback to notify when a service is being added on each interface (as soon
2009 // as probing starts), and call mOffloadCallbacks. This callback is for
2010 // OFFLOAD_CAPABILITY_FILTER_REPLIES offload type.
2011
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002012 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00002013 public void onRegisterServiceSucceeded(int transactionId, NsdServiceInfo registeredInfo) {
2014 mServiceLogs.log("onRegisterServiceSucceeded: transactionId " + transactionId);
2015 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002016 if (clientInfo == null) return;
2017
Paul Hud44e1b72023-06-16 02:07:42 +00002018 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
2019 if (clientRequestId < 0) return;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002020
2021 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
2022 // historical behavior.
2023 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
Paul Hu777ed052023-06-19 13:35:15 +00002024 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu508a0122023-09-11 15:31:33 +08002025 clientInfo.onRegisterServiceSucceeded(clientRequestId, cbInfo, request);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002026 }
2027
2028 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00002029 public void onRegisterServiceFailed(int transactionId, int errorCode) {
2030 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002031 if (clientInfo == null) return;
2032
Paul Hud44e1b72023-06-16 02:07:42 +00002033 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
2034 if (clientRequestId < 0) return;
Paul Hu777ed052023-06-19 13:35:15 +00002035 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu508a0122023-09-11 15:31:33 +08002036 clientInfo.onRegisterServiceFailed(clientRequestId, errorCode, false /* isLegacy */,
2037 transactionId, request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002038 }
2039
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002040 @Override
2041 public void onOffloadStartOrUpdate(@NonNull String interfaceName,
2042 @NonNull OffloadServiceInfo offloadServiceInfo) {
2043 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, false /* isRemove */);
2044 }
2045
2046 @Override
2047 public void onOffloadStop(@NonNull String interfaceName,
2048 @NonNull OffloadServiceInfo offloadServiceInfo) {
2049 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, true /* isRemove */);
2050 }
2051
Paul Hud44e1b72023-06-16 02:07:42 +00002052 private ClientInfo getClientInfoOrLog(int transactionId) {
2053 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002054 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00002055 Log.e(TAG, String.format("Callback for service %d has no client", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002056 }
2057 return clientInfo;
2058 }
2059
Paul Hud44e1b72023-06-16 02:07:42 +00002060 private int getClientRequestIdOrLog(@NonNull ClientInfo info, int transactionId) {
2061 final int clientRequestId = info.getClientRequestId(transactionId);
2062 if (clientRequestId < 0) {
2063 Log.e(TAG, String.format(
2064 "Client request ID not found for service %d", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002065 }
Paul Hud44e1b72023-06-16 02:07:42 +00002066 return clientRequestId;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002067 }
2068 }
2069
Paul Hu2e0a88c2023-03-09 16:05:01 +08002070 private static class ConnectorArgs {
2071 @NonNull public final NsdServiceConnector connector;
2072 @NonNull public final INsdManagerCallback callback;
2073 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002074 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002075
2076 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00002077 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08002078 this.connector = connector;
2079 this.callback = callback;
2080 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002081 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002082 }
2083 }
2084
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002085 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08002086 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09002087 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu101dbf52023-08-09 16:05:20 +08002088 final int uid = mDeps.getCallingUid();
2089 if (cb == null) {
2090 throw new IllegalArgumentException("Unknown client callback from uid=" + uid);
2091 }
Paul Hu2e0a88c2023-03-09 16:05:01 +08002092 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002093 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00002094 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
Paul Hu101dbf52023-08-09 16:05:20 +08002095 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend, uid)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002096 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07002097 }
2098
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002099 private static class ListenerArgs {
2100 public final NsdServiceConnector connector;
2101 public final NsdServiceInfo serviceInfo;
2102 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
2103 this.connector = connector;
2104 this.serviceInfo = serviceInfo;
2105 }
2106 }
2107
Yuyang Huang86d083f2023-12-12 19:56:41 +09002108 private static class AdvertisingArgs {
2109 public final NsdServiceConnector connector;
2110 public final AdvertisingRequest advertisingRequest;
2111
2112 AdvertisingArgs(NsdServiceConnector connector, AdvertisingRequest advertisingRequest) {
2113 this.connector = connector;
2114 this.advertisingRequest = advertisingRequest;
2115 }
2116 }
2117
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002118 private class NsdServiceConnector extends INsdServiceConnector.Stub
2119 implements IBinder.DeathRecipient {
Yuyang Huang86d083f2023-12-12 19:56:41 +09002120
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002121 @Override
Yuyang Huang86d083f2023-12-12 19:56:41 +09002122 public void registerService(int listenerKey, AdvertisingRequest advertisingRequest)
2123 throws RemoteException {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002124 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2125 NsdManager.REGISTER_SERVICE, 0, listenerKey,
Yuyang Huang86d083f2023-12-12 19:56:41 +09002126 new AdvertisingArgs(this, advertisingRequest)
2127 ));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002128 }
2129
2130 @Override
2131 public void unregisterService(int listenerKey) {
2132 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2133 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
Yuyang Huang86d083f2023-12-12 19:56:41 +09002134 new ListenerArgs(this, (NsdServiceInfo) null)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002135 }
2136
2137 @Override
2138 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
2139 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2140 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
2141 new ListenerArgs(this, serviceInfo)));
2142 }
2143
2144 @Override
2145 public void stopDiscovery(int listenerKey) {
Yuyang Huang86d083f2023-12-12 19:56:41 +09002146 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.STOP_DISCOVERY,
2147 0, listenerKey, new ListenerArgs(this, (NsdServiceInfo) null)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002148 }
2149
2150 @Override
2151 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
2152 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2153 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
2154 new ListenerArgs(this, serviceInfo)));
2155 }
2156
2157 @Override
Paul Hub58deb72022-12-26 09:24:42 +00002158 public void stopResolution(int listenerKey) {
Yuyang Huang86d083f2023-12-12 19:56:41 +09002159 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.STOP_RESOLUTION,
2160 0, listenerKey, new ListenerArgs(this, (NsdServiceInfo) null)));
Paul Hub58deb72022-12-26 09:24:42 +00002161 }
2162
2163 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00002164 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
2165 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2166 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
2167 new ListenerArgs(this, serviceInfo)));
2168 }
2169
2170 @Override
2171 public void unregisterServiceInfoCallback(int listenerKey) {
2172 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2173 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
Yuyang Huang86d083f2023-12-12 19:56:41 +09002174 new ListenerArgs(this, (NsdServiceInfo) null)));
Paul Hu18aeccc2022-12-27 08:48:48 +00002175 }
2176
2177 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002178 public void startDaemon() {
Yuyang Huang86d083f2023-12-12 19:56:41 +09002179 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.DAEMON_STARTUP,
2180 new ListenerArgs(this, (NsdServiceInfo) null)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002181 }
2182
2183 @Override
2184 public void binderDied() {
2185 mNsdStateMachine.sendMessage(
2186 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002187
2188 }
2189
2190 @Override
2191 public void registerOffloadEngine(String ifaceName, IOffloadEngine cb,
2192 @OffloadEngine.OffloadCapability long offloadCapabilities,
2193 @OffloadEngine.OffloadType long offloadTypes) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002194 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002195 Objects.requireNonNull(ifaceName);
2196 Objects.requireNonNull(cb);
2197 mNsdStateMachine.sendMessage(
2198 mNsdStateMachine.obtainMessage(NsdManager.REGISTER_OFFLOAD_ENGINE,
2199 new OffloadEngineInfo(cb, ifaceName, offloadCapabilities,
2200 offloadTypes)));
2201 }
2202
2203 @Override
2204 public void unregisterOffloadEngine(IOffloadEngine cb) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002205 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002206 Objects.requireNonNull(cb);
2207 mNsdStateMachine.sendMessage(
2208 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_OFFLOAD_ENGINE, cb));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002209 }
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002210
2211 private static void checkOffloadEnginePermission(Context context) {
2212 if (!SdkLevel.isAtLeastT()) {
2213 throw new SecurityException("API is not available in before API level 33");
2214 }
Yuyang Huangd5896e72023-11-28 13:23:59 +09002215
Ken Chena7bae552023-12-27 11:40:57 +08002216 final ArrayList<String> permissionsList = new ArrayList<>(Arrays.asList(NETWORK_STACK,
2217 PERMISSION_MAINLINE_NETWORK_STACK, NETWORK_SETTINGS));
2218
2219 if (SdkLevel.isAtLeastV()) {
2220 // REGISTER_NSD_OFFLOAD_ENGINE was only added to the SDK in V.
2221 permissionsList.add(REGISTER_NSD_OFFLOAD_ENGINE);
2222 } else if (SdkLevel.isAtLeastU()) {
2223 // REGISTER_NSD_OFFLOAD_ENGINE cannot be backport to U. In U, check the DEVICE_POWER
2224 // permission instead.
2225 permissionsList.add(DEVICE_POWER);
Yuyang Huangd5896e72023-11-28 13:23:59 +09002226 }
2227
Ken Chena7bae552023-12-27 11:40:57 +08002228 if (PermissionUtils.checkAnyPermissionOf(context,
2229 permissionsList.toArray(new String[0]))) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002230 return;
2231 }
2232 throw new SecurityException("Requires one of the following permissions: "
Ken Chena7bae552023-12-27 11:40:57 +08002233 + String.join(", ", permissionsList) + ".");
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002234 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002235 }
2236
Hugo Benichi912db992017-04-24 16:41:03 +09002237 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07002238 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07002239 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09002240 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
2241 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07002242 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07002243 }
2244
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002245 private int getUniqueId() {
2246 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
2247 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002248 }
2249
Paul Hud44e1b72023-06-16 02:07:42 +00002250 private boolean registerService(int transactionId, NsdServiceInfo service) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002251 if (mMDnsManager == null) {
2252 Log.wtf(TAG, "registerService: mMDnsManager is null");
2253 return false;
2254 }
2255
Hugo Benichi6d706442017-04-24 16:19:58 +09002256 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002257 Log.d(TAG, "registerService: " + transactionId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002258 }
Hugo Benichi6d706442017-04-24 16:19:58 +09002259 String name = service.getServiceName();
2260 String type = service.getServiceType();
2261 int port = service.getPort();
2262 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002263 final int registerInterface = getNetworkInterfaceIndex(service);
2264 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08002265 Log.e(TAG, "Interface to register service on not found");
2266 return false;
2267 }
Paul Hud44e1b72023-06-16 02:07:42 +00002268 return mMDnsManager.registerService(
2269 transactionId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002270 }
2271
Paul Hud44e1b72023-06-16 02:07:42 +00002272 private boolean unregisterService(int transactionId) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002273 if (mMDnsManager == null) {
2274 Log.wtf(TAG, "unregisterService: mMDnsManager is null");
2275 return false;
2276 }
Paul Hud44e1b72023-06-16 02:07:42 +00002277 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002278 }
2279
Paul Hud44e1b72023-06-16 02:07:42 +00002280 private boolean discoverServices(int transactionId, NsdServiceInfo serviceInfo) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002281 if (mMDnsManager == null) {
2282 Log.wtf(TAG, "discoverServices: mMDnsManager is null");
2283 return false;
2284 }
2285
paulhu2b9ed952022-02-10 21:58:32 +08002286 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002287 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
2288 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002289 Log.e(TAG, "Interface to discover service on not found");
2290 return false;
2291 }
Paul Hud44e1b72023-06-16 02:07:42 +00002292 return mMDnsManager.discover(transactionId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002293 }
2294
Paul Hud44e1b72023-06-16 02:07:42 +00002295 private boolean stopServiceDiscovery(int transactionId) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002296 if (mMDnsManager == null) {
2297 Log.wtf(TAG, "stopServiceDiscovery: mMDnsManager is null");
2298 return false;
2299 }
Paul Hud44e1b72023-06-16 02:07:42 +00002300 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002301 }
2302
Paul Hud44e1b72023-06-16 02:07:42 +00002303 private boolean resolveService(int transactionId, NsdServiceInfo service) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002304 if (mMDnsManager == null) {
2305 Log.wtf(TAG, "resolveService: mMDnsManager is null");
2306 return false;
2307 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002308 final String name = service.getServiceName();
2309 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002310 final int resolveInterface = getNetworkInterfaceIndex(service);
2311 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002312 Log.e(TAG, "Interface to resolve service on not found");
2313 return false;
2314 }
Paul Hud44e1b72023-06-16 02:07:42 +00002315 return mMDnsManager.resolve(transactionId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002316 }
2317
2318 /**
2319 * Guess the interface to use to resolve or discover a service on a specific network.
2320 *
2321 * This is an imperfect guess, as for example the network may be gone or not yet fully
2322 * registered. This is fine as failing is correct if the network is gone, and a client
2323 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
2324 * this is to support the legacy mdnsresponder implementation, which historically resolved
2325 * services on an unspecified network.
2326 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002327 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
2328 final Network network = serviceInfo.getNetwork();
2329 if (network == null) {
2330 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
2331 // provided by NsdService from discovery results, and the service was found on an
2332 // interface that has no app-usable Network).
2333 if (serviceInfo.getInterfaceIndex() != 0) {
2334 return serviceInfo.getInterfaceIndex();
2335 }
2336 return IFACE_IDX_ANY;
2337 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002338
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002339 String interfaceName = getNetworkInterfaceName(network);
2340 if (interfaceName == null) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002341 return IFACE_IDX_ANY;
2342 }
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002343 return getNetworkInterfaceIndexByName(interfaceName);
2344 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002345
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002346 private String getNetworkInterfaceName(@Nullable Network network) {
2347 if (network == null) {
2348 return null;
2349 }
2350 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
2351 if (cm == null) {
2352 Log.wtf(TAG, "No ConnectivityManager");
2353 return null;
2354 }
2355 final LinkProperties lp = cm.getLinkProperties(network);
2356 if (lp == null) {
2357 return null;
2358 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002359 // Only resolve on non-stacked interfaces
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002360 return lp.getInterfaceName();
2361 }
2362
2363 private int getNetworkInterfaceIndexByName(final String ifaceName) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002364 final NetworkInterface iface;
2365 try {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002366 iface = NetworkInterface.getByName(ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002367 } catch (SocketException e) {
2368 Log.e(TAG, "Error querying interface", e);
2369 return IFACE_IDX_ANY;
2370 }
2371
2372 if (iface == null) {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002373 Log.e(TAG, "Interface not found: " + ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002374 return IFACE_IDX_ANY;
2375 }
2376
2377 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002378 }
2379
Paul Hud44e1b72023-06-16 02:07:42 +00002380 private boolean stopResolveService(int transactionId) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002381 if (mMDnsManager == null) {
2382 Log.wtf(TAG, "stopResolveService: mMDnsManager is null");
2383 return false;
2384 }
Paul Hud44e1b72023-06-16 02:07:42 +00002385 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002386 }
2387
Paul Hud44e1b72023-06-16 02:07:42 +00002388 private boolean getAddrInfo(int transactionId, String hostname, int interfaceIdx) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002389 if (mMDnsManager == null) {
2390 Log.wtf(TAG, "getAddrInfo: mMDnsManager is null");
2391 return false;
2392 }
Paul Hud44e1b72023-06-16 02:07:42 +00002393 return mMDnsManager.getServiceAddress(transactionId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002394 }
2395
Paul Hud44e1b72023-06-16 02:07:42 +00002396 private boolean stopGetAddrInfo(int transactionId) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002397 if (mMDnsManager == null) {
2398 Log.wtf(TAG, "stopGetAddrInfo: mMDnsManager is null");
2399 return false;
2400 }
Paul Hud44e1b72023-06-16 02:07:42 +00002401 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002402 }
2403
2404 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00002405 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2406 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002407
Paul Hub2e67d32023-04-18 05:50:14 +00002408 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2409 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07002410 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00002411
2412 // Dump service and clients logs
2413 pw.println();
Paul Hu14667de2023-04-17 22:42:47 +08002414 pw.println("Logs:");
Paul Hub2e67d32023-04-18 05:50:14 +00002415 pw.increaseIndent();
2416 mServiceLogs.reverseDump(pw);
2417 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002418 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002419
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002420 private abstract static class ClientRequest {
Paul Hud44e1b72023-06-16 02:07:42 +00002421 private final int mTransactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002422 private final long mStartTimeMs;
Paul Hu812e9212023-06-20 06:24:53 +00002423 private int mFoundServiceCount = 0;
2424 private int mLostServiceCount = 0;
2425 private final Set<String> mServices = new ArraySet<>();
Paul Hua6bc4632023-06-26 01:18:29 +00002426 private boolean mIsServiceFromCache = false;
Paul Hubad6fe92023-07-24 21:25:22 +08002427 private int mSentQueryCount = NO_SENT_QUERY_COUNT;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002428
Paul Hu812e9212023-06-20 06:24:53 +00002429 private ClientRequest(int transactionId, long startTimeMs) {
Paul Hud44e1b72023-06-16 02:07:42 +00002430 mTransactionId = transactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002431 mStartTimeMs = startTimeMs;
2432 }
2433
Paul Hu812e9212023-06-20 06:24:53 +00002434 public long calculateRequestDurationMs(long stopTimeMs) {
Paul Hu777ed052023-06-19 13:35:15 +00002435 return stopTimeMs - mStartTimeMs;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002436 }
Paul Hu812e9212023-06-20 06:24:53 +00002437
2438 public void onServiceFound(String serviceName) {
2439 mFoundServiceCount++;
2440 if (mServices.size() <= MAX_SERVICES_COUNT_METRIC_PER_CLIENT) {
2441 mServices.add(serviceName);
2442 }
2443 }
2444
2445 public void onServiceLost() {
2446 mLostServiceCount++;
2447 }
2448
2449 public int getFoundServiceCount() {
2450 return mFoundServiceCount;
2451 }
2452
2453 public int getLostServiceCount() {
2454 return mLostServiceCount;
2455 }
2456
2457 public int getServicesCount() {
2458 return mServices.size();
2459 }
Paul Hua6bc4632023-06-26 01:18:29 +00002460
2461 public void setServiceFromCache(boolean isServiceFromCache) {
2462 mIsServiceFromCache = isServiceFromCache;
2463 }
2464
2465 public boolean isServiceFromCache() {
2466 return mIsServiceFromCache;
2467 }
Paul Hubad6fe92023-07-24 21:25:22 +08002468
2469 public void onQuerySent() {
2470 mSentQueryCount++;
2471 }
2472
2473 public int getSentQueryCount() {
2474 return mSentQueryCount;
2475 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002476 }
2477
2478 private static class LegacyClientRequest extends ClientRequest {
2479 private final int mRequestCode;
2480
Paul Hu812e9212023-06-20 06:24:53 +00002481 private LegacyClientRequest(int transactionId, int requestCode, long startTimeMs) {
2482 super(transactionId, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002483 mRequestCode = requestCode;
2484 }
2485 }
2486
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002487 private abstract static class JavaBackendClientRequest extends ClientRequest {
2488 @Nullable
2489 private final Network mRequestedNetwork;
2490
Paul Hu777ed052023-06-19 13:35:15 +00002491 private JavaBackendClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002492 long startTimeMs) {
2493 super(transactionId, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002494 mRequestedNetwork = requestedNetwork;
2495 }
2496
2497 @Nullable
2498 public Network getRequestedNetwork() {
2499 return mRequestedNetwork;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002500 }
2501 }
2502
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002503 private static class AdvertiserClientRequest extends JavaBackendClientRequest {
Paul Hu777ed052023-06-19 13:35:15 +00002504 private AdvertiserClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002505 long startTimeMs) {
2506 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002507 }
2508 }
2509
2510 private static class DiscoveryManagerRequest extends JavaBackendClientRequest {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002511 @NonNull
2512 private final MdnsListener mListener;
2513
Paul Hud44e1b72023-06-16 02:07:42 +00002514 private DiscoveryManagerRequest(int transactionId, @NonNull MdnsListener listener,
Paul Hu812e9212023-06-20 06:24:53 +00002515 @Nullable Network requestedNetwork, long startTimeMs) {
2516 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002517 mListener = listener;
2518 }
2519 }
2520
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002521 /* Information tracked per client */
2522 private class ClientInfo {
2523
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002524 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002525 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002526 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002527 private NsdServiceInfo mResolvedService;
2528
Paul Hud44e1b72023-06-16 02:07:42 +00002529 /* A map from client request ID (listenerKey) to the request */
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002530 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08002531
Luke Huangf7277ed2021-07-12 21:15:10 +08002532 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002533 private boolean mIsPreSClient = false;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002534 private final int mUid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002535 // The flag of using java backend if the client's target SDK >= U
2536 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002537 // Store client logs
2538 private final SharedLog mClientLogs;
Paul Hucdef3532023-06-18 14:47:35 +00002539 // Report the nsd metrics data
2540 private final NetworkNsdReportedMetrics mMetrics;
Luke Huangf7277ed2021-07-12 21:15:10 +08002541
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002542 private ClientInfo(INsdManagerCallback cb, int uid, boolean useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +00002543 SharedLog sharedLog, NetworkNsdReportedMetrics metrics) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002544 mCb = cb;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002545 mUid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002546 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002547 mClientLogs = sharedLog;
2548 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Paul Hucdef3532023-06-18 14:47:35 +00002549 mMetrics = metrics;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002550 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002551
2552 @Override
2553 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06002554 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07002555 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002556 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002557 sb.append("mUseJavaBackend ").append(mUseJavaBackend).append("\n");
2558 sb.append("mUid ").append(mUid).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002559 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002560 int clientRequestId = mClientRequests.keyAt(i);
2561 sb.append("clientRequestId ")
2562 .append(clientRequestId)
2563 .append(" transactionId ").append(mClientRequests.valueAt(i).mTransactionId)
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002564 .append(" type ").append(
2565 mClientRequests.valueAt(i).getClass().getSimpleName())
2566 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07002567 }
2568 return sb.toString();
2569 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002570
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002571 private boolean isPreSClient() {
2572 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08002573 }
2574
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002575 private void setPreSClient() {
2576 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08002577 }
2578
Paul Hu812e9212023-06-20 06:24:53 +00002579 private MdnsListener unregisterMdnsListenerFromRequest(ClientRequest request) {
Paul Hue4f5f252023-02-16 21:13:47 +08002580 final MdnsListener listener =
2581 ((DiscoveryManagerRequest) request).mListener;
2582 mMdnsDiscoveryManager.unregisterListener(
2583 listener.getListenedServiceType(), listener);
Paul Hu812e9212023-06-20 06:24:53 +00002584 return listener;
Paul Hue4f5f252023-02-16 21:13:47 +08002585 }
2586
Dave Plattfeff2af2014-03-07 14:48:22 -08002587 // Remove any pending requests from the global map when we get rid of a client,
2588 // and send cancellations to the daemon.
2589 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00002590 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09002591 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002592 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002593 final int clientRequestId = mClientRequests.keyAt(i);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002594 final ClientRequest request = mClientRequests.valueAt(i);
Paul Hud44e1b72023-06-16 02:07:42 +00002595 final int transactionId = request.mTransactionId;
2596 mTransactionIdToClientInfoMap.remove(transactionId);
paulhub2225702021-11-17 09:35:33 +08002597 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002598 Log.d(TAG, "Terminating clientRequestId " + clientRequestId
2599 + " transactionId " + transactionId
2600 + " type " + mClientRequests.get(clientRequestId));
paulhub2225702021-11-17 09:35:33 +08002601 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002602
2603 if (request instanceof DiscoveryManagerRequest) {
Paul Hu812e9212023-06-20 06:24:53 +00002604 final MdnsListener listener = unregisterMdnsListenerFromRequest(request);
2605 if (listener instanceof DiscoveryListener) {
Paul Hu508a0122023-09-11 15:31:33 +08002606 mMetrics.reportServiceDiscoveryStop(false /* isLegacy */, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00002607 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2608 request.getFoundServiceCount(),
2609 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002610 request.getServicesCount(),
2611 request.getSentQueryCount());
Paul Hu60149052023-07-31 14:26:08 +08002612 } else if (listener instanceof ResolutionListener) {
Paul Hu508a0122023-09-11 15:31:33 +08002613 mMetrics.reportServiceResolutionStop(false /* isLegacy */, transactionId,
Paul Hu60149052023-07-31 14:26:08 +08002614 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Huddce5912023-08-01 10:26:49 +08002615 } else if (listener instanceof ServiceInfoListener) {
2616 mMetrics.reportServiceInfoCallbackUnregistered(transactionId,
2617 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2618 request.getFoundServiceCount(),
2619 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002620 request.isServiceFromCache(),
2621 request.getSentQueryCount());
Paul Hu812e9212023-06-20 06:24:53 +00002622 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002623 continue;
2624 }
2625
2626 if (request instanceof AdvertiserClientRequest) {
Paul Hu043bcd42023-07-14 16:38:25 +08002627 final AdvertiserMetrics metrics =
2628 mAdvertiser.getAdvertiserMetrics(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00002629 mAdvertiser.removeService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002630 mMetrics.reportServiceUnregistration(false /* isLegacy */, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002631 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2632 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2633 metrics.mConflictDuringProbingCount,
2634 metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002635 continue;
2636 }
2637
2638 if (!(request instanceof LegacyClientRequest)) {
2639 throw new IllegalStateException("Unknown request type: " + request.getClass());
2640 }
2641
2642 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08002643 case NsdManager.DISCOVER_SERVICES:
Paul Hud44e1b72023-06-16 02:07:42 +00002644 stopServiceDiscovery(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002645 mMetrics.reportServiceDiscoveryStop(true /* isLegacy */, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00002646 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2647 request.getFoundServiceCount(),
2648 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002649 request.getServicesCount(),
2650 NO_SENT_QUERY_COUNT);
Dave Plattfeff2af2014-03-07 14:48:22 -08002651 break;
2652 case NsdManager.RESOLVE_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002653 stopResolveService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002654 mMetrics.reportServiceResolutionStop(true /* isLegacy */, transactionId,
Paul Hu60149052023-07-31 14:26:08 +08002655 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Dave Plattfeff2af2014-03-07 14:48:22 -08002656 break;
2657 case NsdManager.REGISTER_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002658 unregisterService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002659 mMetrics.reportServiceUnregistration(true /* isLegacy */, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002660 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2661 NO_PACKET /* repliedRequestsCount */,
2662 NO_PACKET /* sentPacketCount */,
2663 0 /* conflictDuringProbingCount */,
2664 0 /* conflictAfterProbingCount */);
Dave Plattfeff2af2014-03-07 14:48:22 -08002665 break;
2666 default:
2667 break;
2668 }
2669 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002670 mClientRequests.clear();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002671 updateMulticastLock();
2672 }
2673
2674 /**
2675 * Returns true if this client has any Java backend request that requests one of the given
2676 * networks.
2677 */
2678 boolean hasAnyJavaBackendRequestForNetworks(@NonNull ArraySet<Network> networks) {
2679 for (int i = 0; i < mClientRequests.size(); i++) {
2680 final ClientRequest req = mClientRequests.valueAt(i);
2681 if (!(req instanceof JavaBackendClientRequest)) {
2682 continue;
2683 }
2684 final Network reqNetwork = ((JavaBackendClientRequest) mClientRequests.valueAt(i))
2685 .getRequestedNetwork();
2686 if (MdnsUtils.isAnyNetworkMatched(reqNetwork, networks)) {
2687 return true;
2688 }
2689 }
2690 return false;
Dave Plattfeff2af2014-03-07 14:48:22 -08002691 }
2692
Paul Hud44e1b72023-06-16 02:07:42 +00002693 // mClientRequests is a sparse array of client request id -> ClientRequest. For a given
2694 // transaction id, return the corresponding client request id.
2695 private int getClientRequestId(final int transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002696 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002697 if (mClientRequests.valueAt(i).mTransactionId == transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002698 return mClientRequests.keyAt(i);
2699 }
Christopher Lane74411222014-04-25 18:39:07 -07002700 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002701 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07002702 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002703
Paul Hub2e67d32023-04-18 05:50:14 +00002704 private void log(String message) {
2705 mClientLogs.log(message);
2706 }
2707
Paul Hu508a0122023-09-11 15:31:33 +08002708 private static boolean isLegacyClientRequest(@NonNull ClientRequest request) {
2709 return !(request instanceof DiscoveryManagerRequest)
2710 && !(request instanceof AdvertiserClientRequest);
2711 }
2712
2713 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info,
2714 ClientRequest request) {
2715 mMetrics.reportServiceDiscoveryStarted(
2716 isLegacyClientRequest(request), request.mTransactionId);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002717 try {
2718 mCb.onDiscoverServicesStarted(listenerKey, info);
2719 } catch (RemoteException e) {
2720 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
2721 }
2722 }
Paul Hu508a0122023-09-11 15:31:33 +08002723 void onDiscoverServicesFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2724 onDiscoverServicesFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2725 0L /* durationMs */);
Paul Hu812e9212023-06-20 06:24:53 +00002726 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002727
Paul Hu508a0122023-09-11 15:31:33 +08002728 void onDiscoverServicesFailed(int listenerKey, int error, boolean isLegacy,
2729 int transactionId, long durationMs) {
2730 mMetrics.reportServiceDiscoveryFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002731 try {
2732 mCb.onDiscoverServicesFailed(listenerKey, error);
2733 } catch (RemoteException e) {
2734 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
2735 }
2736 }
2737
Paul Hu812e9212023-06-20 06:24:53 +00002738 void onServiceFound(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2739 request.onServiceFound(info.getServiceName());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002740 try {
2741 mCb.onServiceFound(listenerKey, info);
2742 } catch (RemoteException e) {
2743 Log.e(TAG, "Error calling onServiceFound(", e);
2744 }
2745 }
2746
Paul Hu812e9212023-06-20 06:24:53 +00002747 void onServiceLost(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2748 request.onServiceLost();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002749 try {
2750 mCb.onServiceLost(listenerKey, info);
2751 } catch (RemoteException e) {
2752 Log.e(TAG, "Error calling onServiceLost(", e);
2753 }
2754 }
2755
2756 void onStopDiscoveryFailed(int listenerKey, int error) {
2757 try {
2758 mCb.onStopDiscoveryFailed(listenerKey, error);
2759 } catch (RemoteException e) {
2760 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
2761 }
2762 }
2763
Paul Hu812e9212023-06-20 06:24:53 +00002764 void onStopDiscoverySucceeded(int listenerKey, ClientRequest request) {
2765 mMetrics.reportServiceDiscoveryStop(
Paul Hu508a0122023-09-11 15:31:33 +08002766 isLegacyClientRequest(request),
Paul Hu812e9212023-06-20 06:24:53 +00002767 request.mTransactionId,
2768 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2769 request.getFoundServiceCount(),
2770 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002771 request.getServicesCount(),
2772 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002773 try {
2774 mCb.onStopDiscoverySucceeded(listenerKey);
2775 } catch (RemoteException e) {
2776 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2777 }
2778 }
2779
Paul Hu508a0122023-09-11 15:31:33 +08002780 void onRegisterServiceFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2781 onRegisterServiceFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2782 0L /* durationMs */);
Paul Hu777ed052023-06-19 13:35:15 +00002783 }
2784
Paul Hu508a0122023-09-11 15:31:33 +08002785 void onRegisterServiceFailed(int listenerKey, int error, boolean isLegacy,
2786 int transactionId, long durationMs) {
2787 mMetrics.reportServiceRegistrationFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002788 try {
2789 mCb.onRegisterServiceFailed(listenerKey, error);
2790 } catch (RemoteException e) {
2791 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2792 }
2793 }
2794
Paul Hu508a0122023-09-11 15:31:33 +08002795 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info,
2796 ClientRequest request) {
2797 mMetrics.reportServiceRegistrationSucceeded(isLegacyClientRequest(request),
2798 request.mTransactionId,
2799 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002800 try {
2801 mCb.onRegisterServiceSucceeded(listenerKey, info);
2802 } catch (RemoteException e) {
2803 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2804 }
2805 }
2806
2807 void onUnregisterServiceFailed(int listenerKey, int error) {
2808 try {
2809 mCb.onUnregisterServiceFailed(listenerKey, error);
2810 } catch (RemoteException e) {
2811 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2812 }
2813 }
2814
Paul Hu508a0122023-09-11 15:31:33 +08002815 void onUnregisterServiceSucceeded(int listenerKey, ClientRequest request,
Paul Hu043bcd42023-07-14 16:38:25 +08002816 AdvertiserMetrics metrics) {
Paul Hu508a0122023-09-11 15:31:33 +08002817 mMetrics.reportServiceUnregistration(isLegacyClientRequest(request),
2818 request.mTransactionId,
2819 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hu043bcd42023-07-14 16:38:25 +08002820 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2821 metrics.mConflictDuringProbingCount, metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002822 try {
2823 mCb.onUnregisterServiceSucceeded(listenerKey);
2824 } catch (RemoteException e) {
2825 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2826 }
2827 }
2828
Paul Hu508a0122023-09-11 15:31:33 +08002829 void onResolveServiceFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2830 onResolveServiceFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2831 0L /* durationMs */);
Paul Hua6bc4632023-06-26 01:18:29 +00002832 }
2833
Paul Hu508a0122023-09-11 15:31:33 +08002834 void onResolveServiceFailed(int listenerKey, int error, boolean isLegacy,
2835 int transactionId, long durationMs) {
2836 mMetrics.reportServiceResolutionFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002837 try {
2838 mCb.onResolveServiceFailed(listenerKey, error);
2839 } catch (RemoteException e) {
2840 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2841 }
2842 }
2843
Paul Hua6bc4632023-06-26 01:18:29 +00002844 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info,
2845 ClientRequest request) {
2846 mMetrics.reportServiceResolved(
Paul Hu508a0122023-09-11 15:31:33 +08002847 isLegacyClientRequest(request),
Paul Hua6bc4632023-06-26 01:18:29 +00002848 request.mTransactionId,
2849 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hubad6fe92023-07-24 21:25:22 +08002850 request.isServiceFromCache(),
2851 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002852 try {
2853 mCb.onResolveServiceSucceeded(listenerKey, info);
2854 } catch (RemoteException e) {
2855 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2856 }
2857 }
Paul Hub58deb72022-12-26 09:24:42 +00002858
2859 void onStopResolutionFailed(int listenerKey, int error) {
2860 try {
2861 mCb.onStopResolutionFailed(listenerKey, error);
2862 } catch (RemoteException e) {
2863 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2864 }
2865 }
2866
Paul Hu60149052023-07-31 14:26:08 +08002867 void onStopResolutionSucceeded(int listenerKey, ClientRequest request) {
2868 mMetrics.reportServiceResolutionStop(
Paul Hu508a0122023-09-11 15:31:33 +08002869 isLegacyClientRequest(request),
Paul Hu60149052023-07-31 14:26:08 +08002870 request.mTransactionId,
2871 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hub58deb72022-12-26 09:24:42 +00002872 try {
2873 mCb.onStopResolutionSucceeded(listenerKey);
2874 } catch (RemoteException e) {
2875 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2876 }
2877 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002878
2879 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
Paul Huddce5912023-08-01 10:26:49 +08002880 mMetrics.reportServiceInfoCallbackRegistrationFailed(NO_TRANSACTION);
Paul Hu18aeccc2022-12-27 08:48:48 +00002881 try {
2882 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2883 } catch (RemoteException e) {
2884 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2885 }
2886 }
2887
Paul Huddce5912023-08-01 10:26:49 +08002888 void onServiceInfoCallbackRegistered(int transactionId) {
2889 mMetrics.reportServiceInfoCallbackRegistered(transactionId);
2890 }
2891
2892 void onServiceUpdated(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2893 request.onServiceFound(info.getServiceName());
Paul Hu18aeccc2022-12-27 08:48:48 +00002894 try {
2895 mCb.onServiceUpdated(listenerKey, info);
2896 } catch (RemoteException e) {
2897 Log.e(TAG, "Error calling onServiceUpdated", e);
2898 }
2899 }
2900
Paul Huddce5912023-08-01 10:26:49 +08002901 void onServiceUpdatedLost(int listenerKey, ClientRequest request) {
2902 request.onServiceLost();
Paul Hu18aeccc2022-12-27 08:48:48 +00002903 try {
2904 mCb.onServiceUpdatedLost(listenerKey);
2905 } catch (RemoteException e) {
2906 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2907 }
2908 }
2909
Paul Huddce5912023-08-01 10:26:49 +08002910 void onServiceInfoCallbackUnregistered(int listenerKey, ClientRequest request) {
2911 mMetrics.reportServiceInfoCallbackUnregistered(
2912 request.mTransactionId,
2913 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2914 request.getFoundServiceCount(),
2915 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002916 request.isServiceFromCache(),
2917 request.getSentQueryCount());
Paul Hu18aeccc2022-12-27 08:48:48 +00002918 try {
2919 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2920 } catch (RemoteException e) {
2921 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2922 }
2923 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002924 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002925}