blob: cc9d53d56306a0afef904ecd9d32f2d665f699c3 [file] [log] [blame]
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001/*
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002 * Copyright (C) 2021 The Android Open Source Project
Irfan Sheriff77ec5582012-03-22 17:01:39 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Yuyang Huangd5896e72023-11-28 13:23:59 +090019import static android.Manifest.permission.DEVICE_POWER;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090020import static android.Manifest.permission.NETWORK_SETTINGS;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090021import static android.Manifest.permission.NETWORK_STACK;
paulhu2b9ed952022-02-10 21:58:32 +080022import static android.net.ConnectivityManager.NETID_UNSET;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090023import static android.net.NetworkCapabilities.TRANSPORT_VPN;
24import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090025import static android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK;
Paul Hu019621e2023-01-13 23:26:49 +080026import static android.net.nsd.NsdManager.MDNS_DISCOVERY_MANAGER_EVENT;
paulhu2b9ed952022-02-10 21:58:32 +080027import static android.net.nsd.NsdManager.MDNS_SERVICE_EVENT;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +090028import static android.net.nsd.NsdManager.RESOLVE_SERVICE_SUCCEEDED;
Yuyang Huang86d083f2023-12-12 19:56:41 +090029import static android.net.nsd.NsdManager.TYPE_REGEX;
30import static android.net.nsd.NsdManager.TYPE_SUBTYPE_LABEL_REGEX;
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +090031import static android.provider.DeviceConfig.NAMESPACE_TETHERING;
Motomu Utsumied4e7ec2023-09-13 14:58:32 +090032
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090033import static com.android.modules.utils.build.SdkLevel.isAtLeastU;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090034import static com.android.networkstack.apishim.ConstantsShim.REGISTER_NSD_OFFLOAD_ENGINE;
Paul Hu043bcd42023-07-14 16:38:25 +080035import static com.android.server.connectivity.mdns.MdnsAdvertiser.AdvertiserMetrics;
36import static com.android.server.connectivity.mdns.MdnsConstants.NO_PACKET;
Yuyang Huangde802c82023-05-02 17:14:22 +090037import static com.android.server.connectivity.mdns.MdnsRecord.MAX_LABEL_LENGTH;
Paul Hucdef3532023-06-18 14:47:35 +000038import static com.android.server.connectivity.mdns.util.MdnsUtils.Clock;
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090039
Paul Hu23fa2022023-01-13 22:57:24 +080040import android.annotation.NonNull;
Paul Hu4bd98ef2023-01-12 13:42:07 +080041import android.annotation.Nullable;
Yuyang Huangfc831702023-08-21 17:48:48 +090042import android.annotation.RequiresApi;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090043import android.app.ActivityManager;
paulhua262cc12019-08-12 16:25:11 +080044import android.content.Context;
Irfan Sheriff75006652012-04-17 23:15:29 -070045import android.content.Intent;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090046import android.net.ConnectivityManager;
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +090047import android.net.INetd;
Paul Hu75069ed2023-01-14 00:31:09 +080048import android.net.InetAddresses;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090049import android.net.LinkProperties;
50import android.net.Network;
paulhu2b9ed952022-02-10 21:58:32 +080051import android.net.mdns.aidl.DiscoveryInfo;
52import android.net.mdns.aidl.GetAddressInfo;
53import android.net.mdns.aidl.IMDnsEventListener;
54import android.net.mdns.aidl.RegistrationInfo;
55import android.net.mdns.aidl.ResolutionInfo;
Yuyang Huang86d083f2023-12-12 19:56:41 +090056import android.net.nsd.AdvertisingRequest;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070057import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090058import android.net.nsd.INsdManagerCallback;
59import android.net.nsd.INsdServiceConnector;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090060import android.net.nsd.IOffloadEngine;
paulhu2b9ed952022-02-10 21:58:32 +080061import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070062import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080063import android.net.nsd.NsdServiceInfo;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090064import android.net.nsd.OffloadEngine;
65import android.net.nsd.OffloadServiceInfo;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090066import android.net.wifi.WifiManager;
Paul Hub2e67d32023-04-18 05:50:14 +000067import android.os.Binder;
Yuyang Huangfc831702023-08-21 17:48:48 +090068import android.os.Build;
Hugo Benichi803a2f02017-04-24 11:35:06 +090069import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080070import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090071import android.os.IBinder;
Paul Hu4bd98ef2023-01-12 13:42:07 +080072import android.os.Looper;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070073import android.os.Message;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090074import android.os.RemoteCallbackList;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090075import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070076import android.os.UserHandle;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090077import android.provider.DeviceConfig;
Paul Hu23fa2022023-01-13 22:57:24 +080078import android.text.TextUtils;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090079import android.util.ArraySet;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090080import android.util.Log;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +090081import android.util.Pair;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070082import android.util.SparseArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070083
paulhua262cc12019-08-12 16:25:11 +080084import com.android.internal.annotations.VisibleForTesting;
Paul Hub2e67d32023-04-18 05:50:14 +000085import com.android.internal.util.IndentingPrintWriter;
paulhua262cc12019-08-12 16:25:11 +080086import com.android.internal.util.State;
87import com.android.internal.util.StateMachine;
Paul Hucdef3532023-06-18 14:47:35 +000088import com.android.metrics.NetworkNsdReportedMetrics;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090089import com.android.modules.utils.build.SdkLevel;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090090import com.android.net.module.util.CollectionUtils;
Paul Hu4bd98ef2023-01-12 13:42:07 +080091import com.android.net.module.util.DeviceConfigUtils;
Yuyang Huanga6a6ff92023-04-24 13:33:34 +090092import com.android.net.module.util.InetAddressUtils;
paulhu3ffffe72021-09-16 10:15:22 +080093import com.android.net.module.util.PermissionUtils;
Paul Hub2e67d32023-04-18 05:50:14 +000094import com.android.net.module.util.SharedLog;
Paul Hu4bd98ef2023-01-12 13:42:07 +080095import com.android.server.connectivity.mdns.ExecutorProvider;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090096import com.android.server.connectivity.mdns.MdnsAdvertiser;
Yuyang Huange5cba9c2023-11-02 18:05:47 +090097import com.android.server.connectivity.mdns.MdnsAdvertisingOptions;
Paul Hu4bd98ef2023-01-12 13:42:07 +080098import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
Yuyang Huangb96a0712023-09-07 15:13:15 +090099import com.android.server.connectivity.mdns.MdnsFeatureFlags;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900100import com.android.server.connectivity.mdns.MdnsInterfaceSocket;
Paul Hu4bd98ef2023-01-12 13:42:07 +0800101import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
Paul Hu23fa2022023-01-13 22:57:24 +0800102import com.android.server.connectivity.mdns.MdnsSearchOptions;
103import com.android.server.connectivity.mdns.MdnsServiceBrowserListener;
104import com.android.server.connectivity.mdns.MdnsServiceInfo;
Paul Hu4bd98ef2023-01-12 13:42:07 +0800105import com.android.server.connectivity.mdns.MdnsSocketProvider;
Yuyang Huangde802c82023-05-02 17:14:22 +0900106import com.android.server.connectivity.mdns.util.MdnsUtils;
paulhua262cc12019-08-12 16:25:11 +0800107
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700108import java.io.FileDescriptor;
109import java.io.PrintWriter;
Yuyang Huangaa0e9602023-03-17 12:43:09 +0900110import java.net.Inet6Address;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700111import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900112import java.net.NetworkInterface;
113import java.net.SocketException;
114import java.net.UnknownHostException;
Paul Hu2b865912023-03-06 14:27:53 +0800115import java.util.ArrayList;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900116import java.util.Arrays;
Kangping Dong5af24b62023-12-10 21:41:16 +0800117import java.util.Collection;
Yuyang Huang170d42f2023-12-09 15:26:16 +0900118import java.util.Collections;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700119import java.util.HashMap;
Kangping Dong5af24b62023-12-10 21:41:16 +0800120import java.util.LinkedHashMap;
Paul Hu23fa2022023-01-13 22:57:24 +0800121import java.util.List;
Paul Hu75069ed2023-01-14 00:31:09 +0800122import java.util.Map;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900123import java.util.Objects;
Paul Hu812e9212023-06-20 06:24:53 +0000124import java.util.Set;
Paul Hu23fa2022023-01-13 22:57:24 +0800125import java.util.regex.Matcher;
126import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700127
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700128/**
129 * Network Service Discovery Service handles remote service discovery operation requests by
130 * implementing the INsdManager interface.
131 *
132 * @hide
133 */
Yuyang Huangfc831702023-08-21 17:48:48 +0900134@RequiresApi(Build.VERSION_CODES.TIRAMISU)
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700135public class NsdService extends INsdManager.Stub {
136 private static final String TAG = "NsdService";
137 private static final String MDNS_TAG = "mDnsConnector";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900138 /**
139 * Enable discovery using the Java DiscoveryManager, instead of the legacy mdnsresponder
140 * implementation.
141 */
Paul Hu4bd98ef2023-01-12 13:42:07 +0800142 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +0800143 private static final String LOCAL_DOMAIN_NAME = "local";
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700144
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900145 /**
146 * Enable advertising using the Java MdnsAdvertiser, instead of the legacy mdnsresponder
147 * implementation.
148 */
149 private static final String MDNS_ADVERTISER_VERSION = "mdns_advertiser_version";
150
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900151 /**
152 * Comma-separated list of type:flag mappings indicating the flags to use to allowlist
153 * discovery/advertising using MdnsDiscoveryManager / MdnsAdvertiser for a given type.
154 *
155 * For example _mytype._tcp.local and _othertype._tcp.local would be configured with:
156 * _mytype._tcp:mytype,_othertype._tcp.local:othertype
157 *
158 * In which case the flags:
159 * "mdns_discovery_manager_allowlist_mytype_version",
160 * "mdns_advertiser_allowlist_mytype_version",
161 * "mdns_discovery_manager_allowlist_othertype_version",
162 * "mdns_advertiser_allowlist_othertype_version"
163 * would be used to toggle MdnsDiscoveryManager / MdnsAdvertiser for each type. The flags will
164 * be read with
Motomu Utsumi624aeb42023-08-15 15:52:27 +0900165 * {@link DeviceConfigUtils#isTetheringFeatureEnabled}
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900166 *
167 * @see #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX
168 * @see #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX
169 * @see #MDNS_ALLOWLIST_FLAG_SUFFIX
170 */
171 private static final String MDNS_TYPE_ALLOWLIST_FLAGS = "mdns_type_allowlist_flags";
172
173 private static final String MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX =
174 "mdns_discovery_manager_allowlist_";
175 private static final String MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX =
176 "mdns_advertiser_allowlist_";
177 private static final String MDNS_ALLOWLIST_FLAG_SUFFIX = "_version";
178
Yuyang Huang86d083f2023-12-12 19:56:41 +0900179
Kangping Dong5af24b62023-12-10 21:41:16 +0800180
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900181 @VisibleForTesting
182 static final String MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
183 "mdns_config_running_app_active_importance_cutoff";
184 @VisibleForTesting
185 static final int DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
186 ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
187 private final int mRunningAppActiveImportanceCutoff;
188
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900189 public static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +0000190 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900191 private static final int IFACE_IDX_ANY = 0;
Paul Hu812e9212023-06-20 06:24:53 +0000192 private static final int MAX_SERVICES_COUNT_METRIC_PER_CLIENT = 100;
193 @VisibleForTesting
194 static final int NO_TRANSACTION = -1;
Paul Hubad6fe92023-07-24 21:25:22 +0800195 private static final int NO_SENT_QUERY_COUNT = 0;
196 private static final int DISCOVERY_QUERY_SENT_CALLBACK = 1000;
Kangping Dong5af24b62023-12-10 21:41:16 +0800197 private static final int MAX_SUBTYPE_COUNT = 100;
Paul Hu14667de2023-04-17 22:42:47 +0800198 private static final SharedLog LOGGER = new SharedLog("serviceDiscovery");
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700199
Hugo Benichi32be63d2017-04-05 14:06:11 +0900200 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900201 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +0800202 private final MDnsManager mMDnsManager;
203 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900204 @NonNull
205 private final Dependencies mDeps;
206 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800207 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900208 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800209 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900210 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800211 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900212 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900213 private final MdnsAdvertiser mAdvertiser;
Paul Hu777ed052023-06-19 13:35:15 +0000214 @NonNull
215 private final Clock mClock;
Paul Hu14667de2023-04-17 22:42:47 +0800216 private final SharedLog mServiceLogs = LOGGER.forSubComponent(TAG);
Paul Hu23fa2022023-01-13 22:57:24 +0800217 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800218 // state machine thread. If change this outside state machine, it will need to introduce
219 // synchronization.
220 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800221 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700222
223 /**
224 * Clients receiving asynchronous messages
225 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900226 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700227
Paul Hud44e1b72023-06-16 02:07:42 +0000228 /* A map from transaction(unique) id to client info */
229 private final SparseArray<ClientInfo> mTransactionIdToClientInfoMap = new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700230
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900231 // Note this is not final to avoid depending on the Wi-Fi service starting before NsdService
232 @Nullable
233 private WifiManager.MulticastLock mHeldMulticastLock;
234 // Fulfilled network requests that require the Wi-Fi lock: key is the obtained Network
235 // (non-null), value is the requested Network (nullable)
236 @NonNull
237 private final ArraySet<Network> mWifiLockRequiredNetworks = new ArraySet<>();
238 @NonNull
239 private final ArraySet<Integer> mRunningAppActiveUids = new ArraySet<>();
240
Luke Huang05298582021-06-13 16:52:05 +0000241 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700242
Hugo Benichi32be63d2017-04-05 14:06:11 +0900243 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700244 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800245 // The count of the connected legacy clients.
246 private int mLegacyClientCount = 0;
Paul Hub2e67d32023-04-18 05:50:14 +0000247 // The number of client that ever connected.
248 private int mClientNumberId = 1;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700249
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900250 private final RemoteCallbackList<IOffloadEngine> mOffloadEngines =
251 new RemoteCallbackList<>();
252
253 private static class OffloadEngineInfo {
254 @NonNull final String mInterfaceName;
255 final long mOffloadCapabilities;
256 final long mOffloadType;
257 @NonNull final IOffloadEngine mOffloadEngine;
258
259 OffloadEngineInfo(@NonNull IOffloadEngine offloadEngine,
260 @NonNull String interfaceName, long capabilities, long offloadType) {
261 this.mOffloadEngine = offloadEngine;
262 this.mInterfaceName = interfaceName;
263 this.mOffloadCapabilities = capabilities;
264 this.mOffloadType = offloadType;
265 }
266 }
267
Paul Hu812e9212023-06-20 06:24:53 +0000268 @VisibleForTesting
269 static class MdnsListener implements MdnsServiceBrowserListener {
Paul Hud44e1b72023-06-16 02:07:42 +0000270 protected final int mClientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800271 protected final int mTransactionId;
272 @NonNull
273 protected final NsdServiceInfo mReqServiceInfo;
274 @NonNull
275 protected final String mListenedServiceType;
276
Paul Hud44e1b72023-06-16 02:07:42 +0000277 MdnsListener(int clientRequestId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
Paul Hu23fa2022023-01-13 22:57:24 +0800278 @NonNull String listenedServiceType) {
Paul Hud44e1b72023-06-16 02:07:42 +0000279 mClientRequestId = clientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800280 mTransactionId = transactionId;
281 mReqServiceInfo = reqServiceInfo;
282 mListenedServiceType = listenedServiceType;
283 }
284
285 @NonNull
286 public String getListenedServiceType() {
287 return mListenedServiceType;
288 }
289
290 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000291 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
292 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800293
294 @Override
295 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
296
297 @Override
298 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
299
300 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000301 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
302 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800303
304 @Override
305 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
306
307 @Override
308 public void onSearchStoppedWithError(int error) { }
309
310 @Override
311 public void onSearchFailedToStart() { }
312
313 @Override
Paul Hubad6fe92023-07-24 21:25:22 +0800314 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
315 int sentQueryTransactionId) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800316
317 @Override
318 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
319 }
320
321 private class DiscoveryListener extends MdnsListener {
322
Paul Hud44e1b72023-06-16 02:07:42 +0000323 DiscoveryListener(int clientRequestId, int transactionId,
324 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
325 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800326 }
327
328 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000329 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
330 boolean isServiceFromCache) {
Paul Hu019621e2023-01-13 23:26:49 +0800331 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
332 NsdManager.SERVICE_FOUND,
Paul Hua6bc4632023-06-26 01:18:29 +0000333 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu23fa2022023-01-13 22:57:24 +0800334 }
335
336 @Override
337 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800338 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
339 NsdManager.SERVICE_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000340 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800341 }
Paul Hubad6fe92023-07-24 21:25:22 +0800342
343 @Override
344 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
345 int sentQueryTransactionId) {
346 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
347 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
348 }
Paul Hu23fa2022023-01-13 22:57:24 +0800349 }
350
Paul Hu75069ed2023-01-14 00:31:09 +0800351 private class ResolutionListener extends MdnsListener {
352
Paul Hud44e1b72023-06-16 02:07:42 +0000353 ResolutionListener(int clientRequestId, int transactionId,
354 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
355 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800356 }
357
358 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000359 public void onServiceFound(MdnsServiceInfo serviceInfo, boolean isServiceFromCache) {
Paul Hu75069ed2023-01-14 00:31:09 +0800360 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
361 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
Paul Hua6bc4632023-06-26 01:18:29 +0000362 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu75069ed2023-01-14 00:31:09 +0800363 }
Paul Hubad6fe92023-07-24 21:25:22 +0800364
365 @Override
366 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
367 int sentQueryTransactionId) {
368 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
369 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
370 }
Paul Hu75069ed2023-01-14 00:31:09 +0800371 }
372
Paul Hu30bd70d2023-02-07 13:20:56 +0000373 private class ServiceInfoListener extends MdnsListener {
374
Paul Hud44e1b72023-06-16 02:07:42 +0000375 ServiceInfoListener(int clientRequestId, int transactionId,
376 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
377 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +0000378 }
379
380 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000381 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
382 boolean isServiceFromCache) {
Paul Hu30bd70d2023-02-07 13:20:56 +0000383 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
384 NsdManager.SERVICE_UPDATED,
Paul Hua6bc4632023-06-26 01:18:29 +0000385 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu30bd70d2023-02-07 13:20:56 +0000386 }
387
388 @Override
389 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) {
390 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
391 NsdManager.SERVICE_UPDATED,
Paul Hud44e1b72023-06-16 02:07:42 +0000392 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000393 }
394
395 @Override
396 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) {
397 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
398 NsdManager.SERVICE_UPDATED_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000399 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000400 }
Paul Hubad6fe92023-07-24 21:25:22 +0800401
402 @Override
403 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
404 int sentQueryTransactionId) {
405 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
406 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
407 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000408 }
409
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900410 private class SocketRequestMonitor implements MdnsSocketProvider.SocketRequestMonitor {
411 @Override
412 public void onSocketRequestFulfilled(@Nullable Network socketNetwork,
413 @NonNull MdnsInterfaceSocket socket, @NonNull int[] transports) {
414 // The network may be null for Wi-Fi SoftAp interfaces (tethering), but there is no APF
415 // filtering on such interfaces, so taking the multicast lock is not necessary to
416 // disable APF filtering of multicast.
417 if (socketNetwork == null
418 || !CollectionUtils.contains(transports, TRANSPORT_WIFI)
419 || CollectionUtils.contains(transports, TRANSPORT_VPN)) {
420 return;
421 }
422
423 if (mWifiLockRequiredNetworks.add(socketNetwork)) {
424 updateMulticastLock();
425 }
426 }
427
428 @Override
429 public void onSocketDestroyed(@Nullable Network socketNetwork,
430 @NonNull MdnsInterfaceSocket socket) {
431 if (mWifiLockRequiredNetworks.remove(socketNetwork)) {
432 updateMulticastLock();
433 }
434 }
435 }
436
437 private class UidImportanceListener implements ActivityManager.OnUidImportanceListener {
438 private final Handler mHandler;
439
440 private UidImportanceListener(Handler handler) {
441 mHandler = handler;
442 }
443
444 @Override
445 public void onUidImportance(int uid, int importance) {
446 mHandler.post(() -> handleUidImportanceChanged(uid, importance));
447 }
448 }
449
450 private void handleUidImportanceChanged(int uid, int importance) {
451 // Lower importance values are more "important"
452 final boolean modified = importance <= mRunningAppActiveImportanceCutoff
453 ? mRunningAppActiveUids.add(uid)
454 : mRunningAppActiveUids.remove(uid);
455 if (modified) {
456 updateMulticastLock();
457 }
458 }
459
460 /**
461 * Take or release the lock based on updated internal state.
462 *
463 * This determines whether the lock needs to be held based on
464 * {@link #mWifiLockRequiredNetworks}, {@link #mRunningAppActiveUids} and
465 * {@link ClientInfo#mClientRequests}, so it must be called after any of the these have been
466 * updated.
467 */
468 private void updateMulticastLock() {
469 final int needsLockUid = getMulticastLockNeededUid();
470 if (needsLockUid >= 0 && mHeldMulticastLock == null) {
471 final WifiManager wm = mContext.getSystemService(WifiManager.class);
472 if (wm == null) {
473 Log.wtf(TAG, "Got a TRANSPORT_WIFI network without WifiManager");
474 return;
475 }
476 mHeldMulticastLock = wm.createMulticastLock(TAG);
477 mHeldMulticastLock.acquire();
478 mServiceLogs.log("Taking multicast lock for uid " + needsLockUid);
479 } else if (needsLockUid < 0 && mHeldMulticastLock != null) {
480 mHeldMulticastLock.release();
481 mHeldMulticastLock = null;
482 mServiceLogs.log("Released multicast lock");
483 }
484 }
485
486 /**
487 * @return The UID of an app requiring the multicast lock, or -1 if none.
488 */
489 private int getMulticastLockNeededUid() {
490 if (mWifiLockRequiredNetworks.size() == 0) {
491 // Return early if NSD is not active, or not on any relevant network
492 return -1;
493 }
Paul Hud44e1b72023-06-16 02:07:42 +0000494 for (int i = 0; i < mTransactionIdToClientInfoMap.size(); i++) {
495 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.valueAt(i);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900496 if (!mRunningAppActiveUids.contains(clientInfo.mUid)) {
497 // Ignore non-active UIDs
498 continue;
499 }
500
501 if (clientInfo.hasAnyJavaBackendRequestForNetworks(mWifiLockRequiredNetworks)) {
502 return clientInfo.mUid;
503 }
504 }
505 return -1;
506 }
507
Paul Hu019621e2023-01-13 23:26:49 +0800508 /**
509 * Data class of mdns service callback information.
510 */
511 private static class MdnsEvent {
Paul Hud44e1b72023-06-16 02:07:42 +0000512 final int mClientRequestId;
Paul Hubad6fe92023-07-24 21:25:22 +0800513 @Nullable
Paul Hu019621e2023-01-13 23:26:49 +0800514 final MdnsServiceInfo mMdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000515 final boolean mIsServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800516
Paul Hubad6fe92023-07-24 21:25:22 +0800517 MdnsEvent(int clientRequestId) {
518 this(clientRequestId, null /* mdnsServiceInfo */, false /* isServiceFromCache */);
519 }
520
521 MdnsEvent(int clientRequestId, @Nullable MdnsServiceInfo mdnsServiceInfo) {
Paul Hua6bc4632023-06-26 01:18:29 +0000522 this(clientRequestId, mdnsServiceInfo, false /* isServiceFromCache */);
523 }
524
Paul Hubad6fe92023-07-24 21:25:22 +0800525 MdnsEvent(int clientRequestId, @Nullable MdnsServiceInfo mdnsServiceInfo,
Paul Hua6bc4632023-06-26 01:18:29 +0000526 boolean isServiceFromCache) {
Paul Hud44e1b72023-06-16 02:07:42 +0000527 mClientRequestId = clientRequestId;
Paul Hu019621e2023-01-13 23:26:49 +0800528 mMdnsServiceInfo = mdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000529 mIsServiceFromCache = isServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800530 }
531 }
532
Paul Hu77c11182023-10-23 16:17:32 +0800533 // TODO: Use a Handler instead of a StateMachine since there are no state changes.
Irfan Sheriff75006652012-04-17 23:15:29 -0700534 private class NsdStateMachine extends StateMachine {
535
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700536 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700537
538 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700539 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900540 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700541 }
542
Luke Huang92860f92021-06-23 06:29:30 +0000543 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800544 if (mIsDaemonStarted) {
545 if (DBG) Log.d(TAG, "Daemon is already started.");
546 return;
547 }
548 mMDnsManager.registerEventListener(mMDnsEventCallback);
549 mMDnsManager.startDaemon();
550 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000551 maybeScheduleStop();
Paul Hub2e67d32023-04-18 05:50:14 +0000552 mServiceLogs.log("Start mdns_responder daemon");
Luke Huang05298582021-06-13 16:52:05 +0000553 }
554
paulhu2b9ed952022-02-10 21:58:32 +0800555 private void maybeStopDaemon() {
556 if (!mIsDaemonStarted) {
557 if (DBG) Log.d(TAG, "Daemon has not been started.");
558 return;
559 }
560 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
561 mMDnsManager.stopDaemon();
562 mIsDaemonStarted = false;
Paul Hub2e67d32023-04-18 05:50:14 +0000563 mServiceLogs.log("Stop mdns_responder daemon");
paulhu2b9ed952022-02-10 21:58:32 +0800564 }
565
Luke Huang92860f92021-06-23 06:29:30 +0000566 private boolean isAnyRequestActive() {
Paul Hud44e1b72023-06-16 02:07:42 +0000567 return mTransactionIdToClientInfoMap.size() != 0;
Luke Huang92860f92021-06-23 06:29:30 +0000568 }
569
570 private void scheduleStop() {
571 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
572 }
573 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800574 // The native daemon should stay alive and can't be cleanup
575 // if any legacy client connected.
576 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000577 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000578 }
579 }
580
Luke Huang92860f92021-06-23 06:29:30 +0000581 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000582 this.removeMessages(NsdManager.DAEMON_CLEANUP);
583 }
584
Paul Hu23fa2022023-01-13 22:57:24 +0800585 private void maybeStartMonitoringSockets() {
586 if (mIsMonitoringSocketsStarted) {
587 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
588 return;
589 }
590
591 mMdnsSocketProvider.startMonitoringSockets();
592 mIsMonitoringSocketsStarted = true;
593 }
594
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900595 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
596 if (!mIsMonitoringSocketsStarted) return;
597 if (isAnyRequestActive()) return;
598
Paul Hu58f20602023-02-18 11:41:07 +0800599 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800600 mIsMonitoringSocketsStarted = false;
601 }
602
Hugo Benichi803a2f02017-04-24 11:35:06 +0900603 NsdStateMachine(String name, Handler handler) {
604 super(name, handler);
Paul Hu77c11182023-10-23 16:17:32 +0800605 addState(mEnabledState);
paulhu5568f452021-11-30 13:31:29 +0800606 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900607 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700608 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700609 }
610
Irfan Sheriff75006652012-04-17 23:15:29 -0700611 class EnabledState extends State {
612 @Override
613 public void enter() {
614 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700615 }
616
617 @Override
618 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000619 // TODO: it is incorrect to stop the daemon without expunging all requests
620 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000621 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700622 }
623
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700624 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900625 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800626 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700627 return true;
628 }
629 return false;
630 }
631
Paul Hu508a0122023-09-11 15:31:33 +0800632 private ClientRequest storeLegacyRequestMap(int clientRequestId, int transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +0000633 ClientInfo clientInfo, int what, long startTimeMs) {
Paul Hu508a0122023-09-11 15:31:33 +0800634 final LegacyClientRequest request =
635 new LegacyClientRequest(transactionId, what, startTimeMs);
636 clientInfo.mClientRequests.put(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000637 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000638 // Remove the cleanup event because here comes a new request.
639 cancelStop();
Paul Hu508a0122023-09-11 15:31:33 +0800640 return request;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700641 }
642
Paul Hud44e1b72023-06-16 02:07:42 +0000643 private void storeAdvertiserRequestMap(int clientRequestId, int transactionId,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900644 ClientInfo clientInfo, @Nullable Network requestedNetwork) {
Paul Hu777ed052023-06-19 13:35:15 +0000645 clientInfo.mClientRequests.put(clientRequestId, new AdvertiserClientRequest(
Paul Hu812e9212023-06-20 06:24:53 +0000646 transactionId, requestedNetwork, mClock.elapsedRealtime()));
Paul Hud44e1b72023-06-16 02:07:42 +0000647 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900648 updateMulticastLock();
Paul Hu23fa2022023-01-13 22:57:24 +0800649 }
650
Paul Hud44e1b72023-06-16 02:07:42 +0000651 private void removeRequestMap(
652 int clientRequestId, int transactionId, ClientInfo clientInfo) {
653 final ClientRequest existing = clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900654 if (existing == null) return;
Paul Hud44e1b72023-06-16 02:07:42 +0000655 clientInfo.mClientRequests.remove(clientRequestId);
656 mTransactionIdToClientInfoMap.remove(transactionId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900657
658 if (existing instanceof LegacyClientRequest) {
659 maybeScheduleStop();
660 } else {
661 maybeStopMonitoringSocketsIfNoActiveRequest();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900662 updateMulticastLock();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900663 }
664 }
665
Paul Hu508a0122023-09-11 15:31:33 +0800666 private ClientRequest storeDiscoveryManagerRequestMap(int clientRequestId,
667 int transactionId, MdnsListener listener, ClientInfo clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900668 @Nullable Network requestedNetwork) {
Paul Hu508a0122023-09-11 15:31:33 +0800669 final DiscoveryManagerRequest request = new DiscoveryManagerRequest(transactionId,
670 listener, requestedNetwork, mClock.elapsedRealtime());
671 clientInfo.mClientRequests.put(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000672 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900673 updateMulticastLock();
Paul Hu508a0122023-09-11 15:31:33 +0800674 return request;
Paul Hu23fa2022023-01-13 22:57:24 +0800675 }
676
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900677 /**
678 * Truncate a service name to up to 63 UTF-8 bytes.
679 *
680 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
681 * names used in registerService follows historical behavior (see mdnsresponder
682 * handle_regservice_request).
683 */
684 @NonNull
685 private String truncateServiceName(@NonNull String originalName) {
Yuyang Huangde802c82023-05-02 17:14:22 +0900686 return MdnsUtils.truncateServiceName(originalName, MAX_LABEL_LENGTH);
Paul Hu23fa2022023-01-13 22:57:24 +0800687 }
688
Paul Hud44e1b72023-06-16 02:07:42 +0000689 private void stopDiscoveryManagerRequest(ClientRequest request, int clientRequestId,
690 int transactionId, ClientInfo clientInfo) {
Paul Hue4f5f252023-02-16 21:13:47 +0800691 clientInfo.unregisterMdnsListenerFromRequest(request);
Paul Hud44e1b72023-06-16 02:07:42 +0000692 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hue4f5f252023-02-16 21:13:47 +0800693 }
694
Paul Hu77c11182023-10-23 16:17:32 +0800695 private ClientInfo getClientInfoForReply(Message msg) {
696 final ListenerArgs args = (ListenerArgs) msg.obj;
697 return mClients.get(args.connector);
698 }
699
Kangping Dong5af24b62023-12-10 21:41:16 +0800700 /**
701 * Returns {@code false} if {@code subtypes} exceeds the maximum number limit or
702 * contains invalid subtype label.
703 */
704 private boolean checkSubtypeLabels(Set<String> subtypes) {
705 if (subtypes.size() > MAX_SUBTYPE_COUNT) {
706 mServiceLogs.e(
707 "Too many subtypes: " + subtypes.size() + " (max = "
708 + MAX_SUBTYPE_COUNT + ")");
709 return false;
710 }
711
712 for (String subtype : subtypes) {
713 if (!checkSubtypeLabel(subtype)) {
714 mServiceLogs.e("Subtype " + subtype + " is invalid");
715 return false;
716 }
717 }
718 return true;
719 }
720
721 private Set<String> dedupSubtypeLabels(Collection<String> subtypes) {
722 final Map<String, String> subtypeMap = new LinkedHashMap<>(subtypes.size());
723 for (String subtype : subtypes) {
724 subtypeMap.put(MdnsUtils.toDnsLowerCase(subtype), subtype);
725 }
726 return new ArraySet<>(subtypeMap.values());
727 }
728
Irfan Sheriff75006652012-04-17 23:15:29 -0700729 @Override
730 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900731 final ClientInfo clientInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000732 final int transactionId;
733 final int clientRequestId = msg.arg2;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900734 final OffloadEngineInfo offloadEngineInfo;
Irfan Sheriff75006652012-04-17 23:15:29 -0700735 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800736 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800737 if (DBG) Log.d(TAG, "Discover services");
Yuyang Huang86d083f2023-12-12 19:56:41 +0900738 final ListenerArgs args = (ListenerArgs) msg.obj;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900739 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000740 // If the binder death notification for a INsdManagerCallback was received
741 // before any calls are received by NsdService, the clientInfo would be
742 // cleared and cause NPE. Add a null check here to prevent this corner case.
743 if (clientInfo == null) {
744 Log.e(TAG, "Unknown connector in discovery");
745 break;
746 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700747
748 if (requestLimitReached(clientInfo)) {
Paul Hu508a0122023-09-11 15:31:33 +0800749 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
750 NsdManager.FAILURE_MAX_LIMIT, true /* isLegacy */);
Irfan Sheriff75006652012-04-17 23:15:29 -0700751 break;
752 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700753
Paul Hu23fa2022023-01-13 22:57:24 +0800754 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000755 transactionId = getUniqueId();
Yuyang Huang170d42f2023-12-09 15:26:16 +0900756 final Pair<String, List<String>> typeAndSubtype =
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900757 parseTypeAndSubtype(info.getServiceType());
758 final String serviceType = typeAndSubtype == null
759 ? null : typeAndSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800760 if (clientInfo.mUseJavaBackend
761 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900762 || useDiscoveryManagerForType(serviceType)) {
Yuyang Huang170d42f2023-12-09 15:26:16 +0900763 if (serviceType == null || typeAndSubtype.second.size() > 1) {
Paul Hu508a0122023-09-11 15:31:33 +0800764 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
765 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Paul Hu23fa2022023-01-13 22:57:24 +0800766 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700767 }
Paul Hu23fa2022023-01-13 22:57:24 +0800768
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900769 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800770 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +0000771 final MdnsListener listener = new DiscoveryListener(clientRequestId,
772 transactionId, info, listenServiceType);
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900773 final MdnsSearchOptions.Builder optionsBuilder =
774 MdnsSearchOptions.newBuilder()
775 .setNetwork(info.getNetwork())
Yuyang Huangff963222023-06-01 18:42:42 +0900776 .setRemoveExpiredService(true)
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900777 .setIsPassiveMode(true);
Yuyang Huang170d42f2023-12-09 15:26:16 +0900778 if (!typeAndSubtype.second.isEmpty()) {
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900779 // The parsing ensures subtype starts with an underscore.
780 // MdnsSearchOptions expects the underscore to not be present.
Yuyang Huang170d42f2023-12-09 15:26:16 +0900781 optionsBuilder.addSubtype(
782 typeAndSubtype.second.get(0).substring(1));
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900783 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900784 mMdnsDiscoveryManager.registerListener(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900785 listenServiceType, listener, optionsBuilder.build());
Paul Hu508a0122023-09-11 15:31:33 +0800786 final ClientRequest request = storeDiscoveryManagerRequestMap(
787 clientRequestId, transactionId, listener, clientInfo,
788 info.getNetwork());
789 clientInfo.onDiscoverServicesStarted(clientRequestId, info, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000790 clientInfo.log("Register a DiscoveryListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +0000791 + " for service type:" + listenServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700792 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800793 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000794 if (discoverServices(transactionId, info)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800795 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +0000796 Log.d(TAG, "Discover " + msg.arg2 + " " + transactionId
Paul Hu23fa2022023-01-13 22:57:24 +0800797 + info.getServiceType());
798 }
Paul Hu508a0122023-09-11 15:31:33 +0800799 final ClientRequest request = storeLegacyRequestMap(clientRequestId,
800 transactionId, clientInfo, msg.what,
801 mClock.elapsedRealtime());
Paul Hu812e9212023-06-20 06:24:53 +0000802 clientInfo.onDiscoverServicesStarted(
Paul Hu508a0122023-09-11 15:31:33 +0800803 clientRequestId, info, request);
Paul Hu23fa2022023-01-13 22:57:24 +0800804 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000805 stopServiceDiscovery(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800806 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
807 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Paul Hu23fa2022023-01-13 22:57:24 +0800808 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700809 }
810 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800811 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900812 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800813 if (DBG) Log.d(TAG, "Stop service discovery");
Yuyang Huang86d083f2023-12-12 19:56:41 +0900814 final ListenerArgs args = (ListenerArgs) msg.obj;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900815 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000816 // If the binder death notification for a INsdManagerCallback was received
817 // before any calls are received by NsdService, the clientInfo would be
818 // cleared and cause NPE. Add a null check here to prevent this corner case.
819 if (clientInfo == null) {
820 Log.e(TAG, "Unknown connector in stop discovery");
821 break;
822 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700823
Paul Hud44e1b72023-06-16 02:07:42 +0000824 final ClientRequest request =
825 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900826 if (request == null) {
827 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700828 break;
829 }
Paul Hud44e1b72023-06-16 02:07:42 +0000830 transactionId = request.mTransactionId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900831 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
832 // point, so this needs to check the type of the original request to
833 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900834 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +0000835 stopDiscoveryManagerRequest(
836 request, clientRequestId, transactionId, clientInfo);
Paul Hu812e9212023-06-20 06:24:53 +0000837 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000838 clientInfo.log("Unregister the DiscoveryListener " + transactionId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700839 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000840 removeRequestMap(clientRequestId, transactionId, clientInfo);
841 if (stopServiceDiscovery(transactionId)) {
Paul Hu812e9212023-06-20 06:24:53 +0000842 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hu23fa2022023-01-13 22:57:24 +0800843 } else {
844 clientInfo.onStopDiscoveryFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000845 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu23fa2022023-01-13 22:57:24 +0800846 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700847 }
848 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900849 }
850 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800851 if (DBG) Log.d(TAG, "Register service");
Yuyang Huang86d083f2023-12-12 19:56:41 +0900852 final AdvertisingArgs args = (AdvertisingArgs) msg.obj;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900853 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000854 // If the binder death notification for a INsdManagerCallback was received
855 // before any calls are received by NsdService, the clientInfo would be
856 // cleared and cause NPE. Add a null check here to prevent this corner case.
857 if (clientInfo == null) {
858 Log.e(TAG, "Unknown connector in registration");
859 break;
860 }
861
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700862 if (requestLimitReached(clientInfo)) {
Paul Hu508a0122023-09-11 15:31:33 +0800863 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
864 NsdManager.FAILURE_MAX_LIMIT, true /* isLegacy */);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700865 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700866 }
Yuyang Huang86d083f2023-12-12 19:56:41 +0900867 final AdvertisingRequest advertisingRequest = args.advertisingRequest;
868 if (advertisingRequest == null) {
869 Log.e(TAG, "Unknown advertisingRequest in registration");
870 break;
871 }
872 final NsdServiceInfo serviceInfo = advertisingRequest.getServiceInfo();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900873 final String serviceType = serviceInfo.getServiceType();
Yuyang Huang170d42f2023-12-09 15:26:16 +0900874 final Pair<String, List<String>> typeSubtype = parseTypeAndSubtype(
875 serviceType);
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900876 final String registerServiceType = typeSubtype == null
877 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800878 if (clientInfo.mUseJavaBackend
879 || mDeps.isMdnsAdvertiserEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900880 || useAdvertiserForType(registerServiceType)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900881 if (registerServiceType == null) {
882 Log.e(TAG, "Invalid service type: " + serviceType);
Paul Hu508a0122023-09-11 15:31:33 +0800883 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
884 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900885 break;
886 }
Yuyang Huang86d083f2023-12-12 19:56:41 +0900887 boolean isUpdateOnly = (advertisingRequest.getAdvertisingConfig()
888 & AdvertisingRequest.NSD_ADVERTISING_UPDATE_ONLY) > 0;
889 // If it is an update request, then reuse the old transactionId
890 if (isUpdateOnly) {
891 final ClientRequest existingClientRequest =
892 clientInfo.mClientRequests.get(clientRequestId);
893 if (existingClientRequest == null) {
894 Log.e(TAG, "Invalid update on requestId: " + clientRequestId);
895 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
896 NsdManager.FAILURE_INTERNAL_ERROR,
897 false /* isLegacy */);
898 break;
899 }
900 transactionId = existingClientRequest.mTransactionId;
901 } else {
902 transactionId = getUniqueId();
903 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900904 serviceInfo.setServiceType(registerServiceType);
905 serviceInfo.setServiceName(truncateServiceName(
906 serviceInfo.getServiceName()));
907
Kangping Dong5af24b62023-12-10 21:41:16 +0800908 Set<String> subtypes = new ArraySet<>(serviceInfo.getSubtypes());
Yuyang Huang170d42f2023-12-09 15:26:16 +0900909 for (String subType: typeSubtype.second) {
910 if (!TextUtils.isEmpty(subType)) {
911 subtypes.add(subType);
912 }
Kangping Dong5af24b62023-12-10 21:41:16 +0800913 }
Kangping Dong5af24b62023-12-10 21:41:16 +0800914 subtypes = dedupSubtypeLabels(subtypes);
915
916 if (!checkSubtypeLabels(subtypes)) {
917 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
918 NsdManager.FAILURE_BAD_PARAMETERS, false /* isLegacy */);
919 break;
920 }
921
922 serviceInfo.setSubtypes(subtypes);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900923 maybeStartMonitoringSockets();
Yuyang Huang86d083f2023-12-12 19:56:41 +0900924 final MdnsAdvertisingOptions mdnsAdvertisingOptions =
925 MdnsAdvertisingOptions.newBuilder().setIsOnlyUpdate(
926 isUpdateOnly).build();
Yuyang Huange5cba9c2023-11-02 18:05:47 +0900927 mAdvertiser.addOrUpdateService(transactionId, serviceInfo,
Yuyang Huang86d083f2023-12-12 19:56:41 +0900928 mdnsAdvertisingOptions);
Paul Hud44e1b72023-06-16 02:07:42 +0000929 storeAdvertiserRequestMap(clientRequestId, transactionId, clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900930 serviceInfo.getNetwork());
Irfan Sheriff75006652012-04-17 23:15:29 -0700931 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900932 maybeStartDaemon();
Yuyang Huang86d083f2023-12-12 19:56:41 +0900933 transactionId = getUniqueId();
Paul Hud44e1b72023-06-16 02:07:42 +0000934 if (registerService(transactionId, serviceInfo)) {
935 if (DBG) {
936 Log.d(TAG, "Register " + clientRequestId
937 + " " + transactionId);
938 }
Paul Hua6bc4632023-06-26 01:18:29 +0000939 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
940 msg.what, mClock.elapsedRealtime());
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900941 // Return success after mDns reports success
942 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000943 unregisterService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800944 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
945 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900946 }
947
Irfan Sheriff75006652012-04-17 23:15:29 -0700948 }
949 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900950 }
951 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800952 if (DBG) Log.d(TAG, "unregister service");
Yuyang Huang86d083f2023-12-12 19:56:41 +0900953 final ListenerArgs args = (ListenerArgs) msg.obj;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900954 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000955 // If the binder death notification for a INsdManagerCallback was received
956 // before any calls are received by NsdService, the clientInfo would be
957 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900958 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800959 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700960 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700961 }
Paul Hud44e1b72023-06-16 02:07:42 +0000962 final ClientRequest request =
963 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900964 if (request == null) {
965 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
966 break;
967 }
Paul Hud44e1b72023-06-16 02:07:42 +0000968 transactionId = request.mTransactionId;
969 removeRequestMap(clientRequestId, transactionId, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900970
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900971 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
972 // so this needs to check the type of the original request to unregister
973 // instead of looking at the flag value.
974 if (request instanceof AdvertiserClientRequest) {
Paul Hu043bcd42023-07-14 16:38:25 +0800975 final AdvertiserMetrics metrics =
976 mAdvertiser.getAdvertiserMetrics(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +0000977 mAdvertiser.removeService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800978 clientInfo.onUnregisterServiceSucceeded(
979 clientRequestId, request, metrics);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700980 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000981 if (unregisterService(transactionId)) {
Paul Hu508a0122023-09-11 15:31:33 +0800982 clientInfo.onUnregisterServiceSucceeded(clientRequestId, request,
Paul Hu043bcd42023-07-14 16:38:25 +0800983 new AdvertiserMetrics(NO_PACKET /* repliedRequestsCount */,
984 NO_PACKET /* sentPacketCount */,
985 0 /* conflictDuringProbingCount */,
986 0 /* conflictAfterProbingCount */));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900987 } else {
988 clientInfo.onUnregisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000989 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900990 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700991 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700992 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900993 }
Paul Hu75069ed2023-01-14 00:31:09 +0800994 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800995 if (DBG) Log.d(TAG, "Resolve service");
Yuyang Huang86d083f2023-12-12 19:56:41 +0900996 final ListenerArgs args = (ListenerArgs) msg.obj;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900997 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000998 // If the binder death notification for a INsdManagerCallback was received
999 // before any calls are received by NsdService, the clientInfo would be
1000 // cleared and cause NPE. Add a null check here to prevent this corner case.
1001 if (clientInfo == null) {
1002 Log.e(TAG, "Unknown connector in resolution");
1003 break;
1004 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001005
Paul Hu75069ed2023-01-14 00:31:09 +08001006 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001007 transactionId = getUniqueId();
Yuyang Huang170d42f2023-12-09 15:26:16 +09001008 final Pair<String, List<String>> typeSubtype =
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001009 parseTypeAndSubtype(info.getServiceType());
1010 final String serviceType = typeSubtype == null
1011 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001012 if (clientInfo.mUseJavaBackend
1013 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001014 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +08001015 if (serviceType == null) {
Paul Hu508a0122023-09-11 15:31:33 +08001016 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
1017 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +08001018 break;
1019 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001020 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +08001021
1022 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001023 final MdnsListener listener = new ResolutionListener(clientRequestId,
1024 transactionId, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +08001025 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1026 .setNetwork(info.getNetwork())
1027 .setIsPassiveMode(true)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +09001028 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001029 .setRemoveExpiredService(true)
Paul Hu75069ed2023-01-14 00:31:09 +08001030 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001031 mMdnsDiscoveryManager.registerListener(
1032 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001033 storeDiscoveryManagerRequestMap(clientRequestId, transactionId,
1034 listener, clientInfo, info.getNetwork());
1035 clientInfo.log("Register a ResolutionListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001036 + " for service type:" + resolveServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -07001037 } else {
Paul Hu75069ed2023-01-14 00:31:09 +08001038 if (clientInfo.mResolvedService != null) {
Paul Hu508a0122023-09-11 15:31:33 +08001039 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
1040 NsdManager.FAILURE_ALREADY_ACTIVE, true /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +08001041 break;
1042 }
1043
1044 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +00001045 if (resolveService(transactionId, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +08001046 clientInfo.mResolvedService = new NsdServiceInfo();
Paul Hua6bc4632023-06-26 01:18:29 +00001047 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
1048 msg.what, mClock.elapsedRealtime());
Paul Hu75069ed2023-01-14 00:31:09 +08001049 } else {
Paul Hu508a0122023-09-11 15:31:33 +08001050 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
1051 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +08001052 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001053 }
1054 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001055 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001056 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +00001057 if (DBG) Log.d(TAG, "Stop service resolution");
Yuyang Huang86d083f2023-12-12 19:56:41 +09001058 final ListenerArgs args = (ListenerArgs) msg.obj;
Paul Hub58deb72022-12-26 09:24:42 +00001059 clientInfo = mClients.get(args.connector);
1060 // If the binder death notification for a INsdManagerCallback was received
1061 // before any calls are received by NsdService, the clientInfo would be
1062 // cleared and cause NPE. Add a null check here to prevent this corner case.
1063 if (clientInfo == null) {
1064 Log.e(TAG, "Unknown connector in stop resolution");
1065 break;
1066 }
1067
Paul Hud44e1b72023-06-16 02:07:42 +00001068 final ClientRequest request =
1069 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001070 if (request == null) {
1071 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
1072 break;
1073 }
Paul Hud44e1b72023-06-16 02:07:42 +00001074 transactionId = request.mTransactionId;
Paul Hue4f5f252023-02-16 21:13:47 +08001075 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
1076 // point, so this needs to check the type of the original request to
1077 // unregister instead of looking at the flag value.
1078 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001079 stopDiscoveryManagerRequest(
1080 request, clientRequestId, transactionId, clientInfo);
Paul Hu60149052023-07-31 14:26:08 +08001081 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001082 clientInfo.log("Unregister the ResolutionListener " + transactionId);
Paul Hub58deb72022-12-26 09:24:42 +00001083 } else {
Paul Hud44e1b72023-06-16 02:07:42 +00001084 removeRequestMap(clientRequestId, transactionId, clientInfo);
1085 if (stopResolveService(transactionId)) {
Paul Hu60149052023-07-31 14:26:08 +08001086 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hue4f5f252023-02-16 21:13:47 +08001087 } else {
1088 clientInfo.onStopResolutionFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001089 clientRequestId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hue4f5f252023-02-16 21:13:47 +08001090 }
1091 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +00001092 }
Paul Hub58deb72022-12-26 09:24:42 +00001093 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001094 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001095 case NsdManager.REGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001096 if (DBG) Log.d(TAG, "Register a service callback");
Yuyang Huang86d083f2023-12-12 19:56:41 +09001097 final ListenerArgs args = (ListenerArgs) msg.obj;
Paul Hu18aeccc2022-12-27 08:48:48 +00001098 clientInfo = mClients.get(args.connector);
1099 // If the binder death notification for a INsdManagerCallback was received
1100 // before any calls are received by NsdService, the clientInfo would be
1101 // cleared and cause NPE. Add a null check here to prevent this corner case.
1102 if (clientInfo == null) {
1103 Log.e(TAG, "Unknown connector in callback registration");
1104 break;
1105 }
1106
Paul Hu30bd70d2023-02-07 13:20:56 +00001107 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001108 transactionId = getUniqueId();
Yuyang Huang170d42f2023-12-09 15:26:16 +09001109 final Pair<String, List<String>> typeAndSubtype =
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001110 parseTypeAndSubtype(info.getServiceType());
1111 final String serviceType = typeAndSubtype == null
1112 ? null : typeAndSubtype.first;
Paul Hu30bd70d2023-02-07 13:20:56 +00001113 if (serviceType == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001114 clientInfo.onServiceInfoCallbackRegistrationFailed(clientRequestId,
Paul Hu30bd70d2023-02-07 13:20:56 +00001115 NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +00001116 break;
1117 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001118 final String resolveServiceType = serviceType + ".local";
Paul Hu18aeccc2022-12-27 08:48:48 +00001119
Paul Hu30bd70d2023-02-07 13:20:56 +00001120 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001121 final MdnsListener listener = new ServiceInfoListener(clientRequestId,
1122 transactionId, info, resolveServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +00001123 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1124 .setNetwork(info.getNetwork())
1125 .setIsPassiveMode(true)
1126 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001127 .setRemoveExpiredService(true)
Paul Hu30bd70d2023-02-07 13:20:56 +00001128 .build();
1129 mMdnsDiscoveryManager.registerListener(
1130 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001131 storeDiscoveryManagerRequestMap(clientRequestId, transactionId, listener,
1132 clientInfo, info.getNetwork());
Paul Huddce5912023-08-01 10:26:49 +08001133 clientInfo.onServiceInfoCallbackRegistered(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00001134 clientInfo.log("Register a ServiceInfoListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001135 + " for service type:" + resolveServiceType);
Paul Hu18aeccc2022-12-27 08:48:48 +00001136 break;
Paul Hu30bd70d2023-02-07 13:20:56 +00001137 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001138 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001139 if (DBG) Log.d(TAG, "Unregister a service callback");
Yuyang Huang86d083f2023-12-12 19:56:41 +09001140 final ListenerArgs args = (ListenerArgs) msg.obj;
Paul Hu18aeccc2022-12-27 08:48:48 +00001141 clientInfo = mClients.get(args.connector);
1142 // If the binder death notification for a INsdManagerCallback was received
1143 // before any calls are received by NsdService, the clientInfo would be
1144 // cleared and cause NPE. Add a null check here to prevent this corner case.
1145 if (clientInfo == null) {
1146 Log.e(TAG, "Unknown connector in callback unregistration");
1147 break;
1148 }
1149
Paul Hud44e1b72023-06-16 02:07:42 +00001150 final ClientRequest request =
1151 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001152 if (request == null) {
Paul Hu30bd70d2023-02-07 13:20:56 +00001153 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE_CALLBACK");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001154 break;
1155 }
Paul Hud44e1b72023-06-16 02:07:42 +00001156 transactionId = request.mTransactionId;
Paul Hu30bd70d2023-02-07 13:20:56 +00001157 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001158 stopDiscoveryManagerRequest(
1159 request, clientRequestId, transactionId, clientInfo);
Paul Huddce5912023-08-01 10:26:49 +08001160 clientInfo.onServiceInfoCallbackUnregistered(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001161 clientInfo.log("Unregister the ServiceInfoListener " + transactionId);
Paul Hu18aeccc2022-12-27 08:48:48 +00001162 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001163 loge("Unregister failed with non-DiscoveryManagerRequest.");
Paul Hu18aeccc2022-12-27 08:48:48 +00001164 }
Paul Hu18aeccc2022-12-27 08:48:48 +00001165 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001166 }
paulhu2b9ed952022-02-10 21:58:32 +08001167 case MDNS_SERVICE_EVENT:
1168 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +09001169 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001170 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001171 break;
Paul Hu019621e2023-01-13 23:26:49 +08001172 case MDNS_DISCOVERY_MANAGER_EVENT:
1173 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
1174 return NOT_HANDLED;
1175 }
1176 break;
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001177 case NsdManager.REGISTER_OFFLOAD_ENGINE:
1178 offloadEngineInfo = (OffloadEngineInfo) msg.obj;
1179 // TODO: Limits the number of registrations created by a given class.
1180 mOffloadEngines.register(offloadEngineInfo.mOffloadEngine,
1181 offloadEngineInfo);
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001182 sendAllOffloadServiceInfos(offloadEngineInfo);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001183 break;
1184 case NsdManager.UNREGISTER_OFFLOAD_ENGINE:
1185 mOffloadEngines.unregister((IOffloadEngine) msg.obj);
1186 break;
Paul Hu77c11182023-10-23 16:17:32 +08001187 case NsdManager.REGISTER_CLIENT:
1188 final ConnectorArgs arg = (ConnectorArgs) msg.obj;
1189 final INsdManagerCallback cb = arg.callback;
1190 try {
1191 cb.asBinder().linkToDeath(arg.connector, 0);
1192 final String tag = "Client" + arg.uid + "-" + mClientNumberId++;
1193 final NetworkNsdReportedMetrics metrics =
1194 mDeps.makeNetworkNsdReportedMetrics(
1195 (int) mClock.elapsedRealtime());
1196 clientInfo = new ClientInfo(cb, arg.uid, arg.useJavaBackend,
1197 mServiceLogs.forSubComponent(tag), metrics);
1198 mClients.put(arg.connector, clientInfo);
1199 } catch (RemoteException e) {
1200 Log.w(TAG, "Client request id " + clientRequestId
1201 + " has already died");
1202 }
1203 break;
1204 case NsdManager.UNREGISTER_CLIENT:
1205 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
1206 clientInfo = mClients.remove(connector);
1207 if (clientInfo != null) {
1208 clientInfo.expungeAllRequests();
1209 if (clientInfo.isPreSClient()) {
1210 mLegacyClientCount -= 1;
1211 }
1212 }
1213 maybeStopMonitoringSocketsIfNoActiveRequest();
1214 maybeScheduleStop();
1215 break;
1216 case NsdManager.DAEMON_CLEANUP:
1217 maybeStopDaemon();
1218 break;
1219 // This event should be only sent by the legacy (target SDK < S) clients.
1220 // Mark the sending client as legacy.
1221 case NsdManager.DAEMON_STARTUP:
1222 clientInfo = getClientInfoForReply(msg);
1223 if (clientInfo != null) {
1224 cancelStop();
1225 clientInfo.setPreSClient();
1226 mLegacyClientCount += 1;
1227 maybeStartDaemon();
1228 }
1229 break;
Irfan Sheriff75006652012-04-17 23:15:29 -07001230 default:
Paul Hu77c11182023-10-23 16:17:32 +08001231 Log.wtf(TAG, "Unhandled " + msg);
Hugo Benichif0c84092017-04-05 14:43:29 +09001232 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001233 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001234 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001235 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001236
Paul Hud44e1b72023-06-16 02:07:42 +00001237 private boolean handleMDnsServiceEvent(int code, int transactionId, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001238 NsdServiceInfo servInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001239 ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001240 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001241 Log.e(TAG, String.format(
1242 "transactionId %d for %d has no client mapping", transactionId, code));
Hugo Benichif0c84092017-04-05 14:43:29 +09001243 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001244 }
1245
1246 /* This goes in response as msg.arg2 */
Paul Hud44e1b72023-06-16 02:07:42 +00001247 int clientRequestId = clientInfo.getClientRequestId(transactionId);
1248 if (clientRequestId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -07001249 // This can happen because of race conditions. For example,
1250 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
1251 // and we may get in this situation.
Paul Hud44e1b72023-06-16 02:07:42 +00001252 Log.d(TAG, String.format("%d for transactionId %d that is no longer active",
1253 code, transactionId));
Hugo Benichif0c84092017-04-05 14:43:29 +09001254 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001255 }
Paul Hu812e9212023-06-20 06:24:53 +00001256 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1257 if (request == null) {
1258 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1259 return false;
1260 }
Hugo Benichi32be63d2017-04-05 14:06:11 +09001261 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00001262 Log.d(TAG, String.format(
1263 "MDns service event code:%d transactionId=%d", code, transactionId));
Hugo Benichi32be63d2017-04-05 14:06:11 +09001264 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001265 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +08001266 case IMDnsEventListener.SERVICE_FOUND: {
1267 final DiscoveryInfo info = (DiscoveryInfo) obj;
1268 final String name = info.serviceName;
1269 final String type = info.registrationType;
1270 servInfo = new NsdServiceInfo(name, type);
1271 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001272 if (foundNetId == 0L) {
1273 // Ignore services that do not have a Network: they are not usable
1274 // by apps, as they would need privileged permissions to use
1275 // interfaces that do not have an associated Network.
1276 break;
1277 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +09001278 if (foundNetId == INetd.DUMMY_NET_ID) {
1279 // Ignore services on the dummy0 interface: they are only seen when
1280 // discovering locally advertised services, and are not reachable
1281 // through that interface.
1282 break;
1283 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001284 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001285
1286 clientInfo.onServiceFound(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001287 break;
paulhu2b9ed952022-02-10 21:58:32 +08001288 }
1289 case IMDnsEventListener.SERVICE_LOST: {
1290 final DiscoveryInfo info = (DiscoveryInfo) obj;
1291 final String name = info.serviceName;
1292 final String type = info.registrationType;
1293 final int lostNetId = info.netId;
1294 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001295 // The network could be set to null (netId 0) if it was torn down when the
1296 // service is lost
1297 // TODO: avoid returning null in that case, possibly by remembering
1298 // found services on the same interface index and their network at the time
1299 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001300 clientInfo.onServiceLost(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001301 break;
paulhu2b9ed952022-02-10 21:58:32 +08001302 }
1303 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Paul Hu812e9212023-06-20 06:24:53 +00001304 clientInfo.onDiscoverServicesFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001305 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1306 transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001307 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001308 break;
paulhu2b9ed952022-02-10 21:58:32 +08001309 case IMDnsEventListener.SERVICE_REGISTERED: {
1310 final RegistrationInfo info = (RegistrationInfo) obj;
1311 final String name = info.serviceName;
1312 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Paul Hu508a0122023-09-11 15:31:33 +08001313 clientInfo.onRegisterServiceSucceeded(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001314 break;
paulhu2b9ed952022-02-10 21:58:32 +08001315 }
1316 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Paul Hu777ed052023-06-19 13:35:15 +00001317 clientInfo.onRegisterServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001318 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1319 transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001320 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001321 break;
paulhu2b9ed952022-02-10 21:58:32 +08001322 case IMDnsEventListener.SERVICE_RESOLVED: {
1323 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001324 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +08001325 final String fullName = info.serviceFullName;
1326 while (index < fullName.length() && fullName.charAt(index) != '.') {
1327 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001328 ++index;
1329 }
1330 ++index;
1331 }
paulhu2b9ed952022-02-10 21:58:32 +08001332 if (index >= fullName.length()) {
1333 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001334 break;
1335 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001336
paulhube186602022-04-12 07:18:23 +00001337 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001338 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001339 String type = rest.replace(".local.", "");
1340
Paul Hu30bd70d2023-02-07 13:20:56 +00001341 final NsdServiceInfo serviceInfo = clientInfo.mResolvedService;
Paul Hu18aeccc2022-12-27 08:48:48 +00001342 serviceInfo.setServiceName(name);
1343 serviceInfo.setServiceType(type);
1344 serviceInfo.setPort(info.port);
1345 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001346 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001347
Paul Hud44e1b72023-06-16 02:07:42 +00001348 stopResolveService(transactionId);
1349 removeRequestMap(clientRequestId, transactionId, clientInfo);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001350
Paul Hud44e1b72023-06-16 02:07:42 +00001351 final int transactionId2 = getUniqueId();
1352 if (getAddrInfo(transactionId2, info.hostname, info.interfaceIdx)) {
1353 storeLegacyRequestMap(clientRequestId, transactionId2, clientInfo,
Paul Hua6bc4632023-06-26 01:18:29 +00001354 NsdManager.RESOLVE_SERVICE, request.mStartTimeMs);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001355 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001356 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001357 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1358 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001359 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001360 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001361 }
1362 break;
paulhu2b9ed952022-02-10 21:58:32 +08001363 }
1364 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001365 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001366 stopResolveService(transactionId);
1367 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001368 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001369 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1370 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001371 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001372 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001373 break;
paulhu2b9ed952022-02-10 21:58:32 +08001374 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001375 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001376 stopGetAddrInfo(transactionId);
1377 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001378 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001379 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1380 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001381 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001382 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001383 break;
paulhu2b9ed952022-02-10 21:58:32 +08001384 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001385 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001386 final GetAddressInfo info = (GetAddressInfo) obj;
1387 final String address = info.address;
1388 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001389 InetAddress serviceHost = null;
1390 try {
paulhu2b9ed952022-02-10 21:58:32 +08001391 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001392 } catch (UnknownHostException e) {
1393 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1394 }
1395
1396 // If the resolved service is on an interface without a network, consider it
1397 // as a failure: it would not be usable by apps as they would need
1398 // privileged permissions.
Paul Hu30bd70d2023-02-07 13:20:56 +00001399 if (netId != NETID_UNSET && serviceHost != null) {
1400 clientInfo.mResolvedService.setHost(serviceHost);
1401 setServiceNetworkForCallback(clientInfo.mResolvedService,
1402 netId, info.interfaceIdx);
1403 clientInfo.onResolveServiceSucceeded(
Paul Hua6bc4632023-06-26 01:18:29 +00001404 clientRequestId, clientInfo.mResolvedService, request);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001405 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001406 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001407 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1408 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001409 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001410 }
Paul Hud44e1b72023-06-16 02:07:42 +00001411 stopGetAddrInfo(transactionId);
1412 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001413 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001414 break;
paulhu2b9ed952022-02-10 21:58:32 +08001415 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001416 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001417 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001418 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001419 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001420 }
Paul Hu019621e2023-01-13 23:26:49 +08001421
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001422 @Nullable
1423 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(
1424 final MdnsEvent event, int code) {
Paul Hu019621e2023-01-13 23:26:49 +08001425 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001426 final String[] typeArray = serviceInfo.getServiceType();
1427 final String joinedType;
1428 if (typeArray.length == 0
1429 || !typeArray[typeArray.length - 1].equals(LOCAL_DOMAIN_NAME)) {
1430 Log.wtf(TAG, "MdnsServiceInfo type does not end in .local: "
1431 + Arrays.toString(typeArray));
1432 return null;
1433 } else {
1434 joinedType = TextUtils.join(".",
1435 Arrays.copyOfRange(typeArray, 0, typeArray.length - 1));
1436 }
1437 final String serviceType;
1438 switch (code) {
1439 case NsdManager.SERVICE_FOUND:
1440 case NsdManager.SERVICE_LOST:
1441 // For consistency with historical behavior, discovered service types have
1442 // a dot at the end.
1443 serviceType = joinedType + ".";
1444 break;
1445 case RESOLVE_SERVICE_SUCCEEDED:
1446 // For consistency with historical behavior, resolved service types have
1447 // a dot at the beginning.
1448 serviceType = "." + joinedType;
1449 break;
1450 default:
1451 serviceType = joinedType;
1452 break;
1453 }
Paul Hu019621e2023-01-13 23:26:49 +08001454 final String serviceName = serviceInfo.getServiceInstanceName();
1455 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1456 final Network network = serviceInfo.getNetwork();
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001457 // In MdnsDiscoveryManagerEvent, the Network can be null which means it is a
1458 // network for Tethering interface. In other words, the network == null means the
1459 // network has netId = INetd.LOCAL_NET_ID.
Paul Hu019621e2023-01-13 23:26:49 +08001460 setServiceNetworkForCallback(
1461 servInfo,
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001462 network == null ? INetd.LOCAL_NET_ID : network.netId,
Paul Hu019621e2023-01-13 23:26:49 +08001463 serviceInfo.getInterfaceIndex());
Kangping Dong5af24b62023-12-10 21:41:16 +08001464 servInfo.setSubtypes(dedupSubtypeLabels(serviceInfo.getSubtypes()));
Paul Hu019621e2023-01-13 23:26:49 +08001465 return servInfo;
1466 }
1467
1468 private boolean handleMdnsDiscoveryManagerEvent(
1469 int transactionId, int code, Object obj) {
Paul Hud44e1b72023-06-16 02:07:42 +00001470 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Paul Hu019621e2023-01-13 23:26:49 +08001471 if (clientInfo == null) {
1472 Log.e(TAG, String.format(
1473 "id %d for %d has no client mapping", transactionId, code));
1474 return false;
1475 }
1476
1477 final MdnsEvent event = (MdnsEvent) obj;
Paul Hud44e1b72023-06-16 02:07:42 +00001478 final int clientRequestId = event.mClientRequestId;
Paul Hubad6fe92023-07-24 21:25:22 +08001479 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1480 if (request == null) {
1481 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1482 return false;
1483 }
1484
1485 // Deal with the discovery sent callback
1486 if (code == DISCOVERY_QUERY_SENT_CALLBACK) {
1487 request.onQuerySent();
1488 return true;
1489 }
1490
1491 // Deal with other callbacks.
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001492 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event, code);
1493 // Errors are already logged if null
1494 if (info == null) return false;
Paul Hu83ec7f42023-06-07 18:04:09 +08001495 mServiceLogs.log(String.format(
1496 "MdnsDiscoveryManager event code=%s transactionId=%d",
1497 NsdManager.nameOf(code), transactionId));
Paul Hu019621e2023-01-13 23:26:49 +08001498 switch (code) {
1499 case NsdManager.SERVICE_FOUND:
Paul Hu812e9212023-06-20 06:24:53 +00001500 clientInfo.onServiceFound(clientRequestId, info, request);
Paul Hu319751a2023-01-13 23:56:34 +08001501 break;
1502 case NsdManager.SERVICE_LOST:
Paul Hu812e9212023-06-20 06:24:53 +00001503 clientInfo.onServiceLost(clientRequestId, info, request);
Paul Hu019621e2023-01-13 23:26:49 +08001504 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001505 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
1506 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Paul Hu75069ed2023-01-14 00:31:09 +08001507 info.setPort(serviceInfo.getPort());
1508
1509 Map<String, String> attrs = serviceInfo.getAttributes();
1510 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1511 final String key = kv.getKey();
1512 try {
1513 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1514 } catch (IllegalArgumentException e) {
1515 Log.e(TAG, "Invalid attribute", e);
1516 }
1517 }
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001518 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu2b865912023-03-06 14:27:53 +08001519 if (addresses.size() != 0) {
1520 info.setHostAddresses(addresses);
Paul Hua6bc4632023-06-26 01:18:29 +00001521 request.setServiceFromCache(event.mIsServiceFromCache);
1522 clientInfo.onResolveServiceSucceeded(clientRequestId, info, request);
Paul Hu2b865912023-03-06 14:27:53 +08001523 } else {
1524 // No address. Notify resolution failure.
Paul Hua6bc4632023-06-26 01:18:29 +00001525 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001526 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */,
1527 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001528 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu75069ed2023-01-14 00:31:09 +08001529 }
1530
1531 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001532 if (!(request instanceof DiscoveryManagerRequest)) {
1533 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1534 break;
1535 }
Paul Hud44e1b72023-06-16 02:07:42 +00001536 stopDiscoveryManagerRequest(
1537 request, clientRequestId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001538 break;
1539 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001540 case NsdManager.SERVICE_UPDATED: {
1541 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1542 info.setPort(serviceInfo.getPort());
1543
1544 Map<String, String> attrs = serviceInfo.getAttributes();
1545 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1546 final String key = kv.getKey();
1547 try {
1548 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1549 } catch (IllegalArgumentException e) {
1550 Log.e(TAG, "Invalid attribute", e);
1551 }
1552 }
1553
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001554 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001555 info.setHostAddresses(addresses);
Paul Huddce5912023-08-01 10:26:49 +08001556 clientInfo.onServiceUpdated(clientRequestId, info, request);
1557 // Set the ServiceFromCache flag only if the service is actually being
1558 // retrieved from the cache. This flag should not be overridden by later
1559 // service updates, which may not be cached.
1560 if (event.mIsServiceFromCache) {
1561 request.setServiceFromCache(true);
1562 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001563 break;
1564 }
1565 case NsdManager.SERVICE_UPDATED_LOST:
Paul Huddce5912023-08-01 10:26:49 +08001566 clientInfo.onServiceUpdatedLost(clientRequestId, request);
Paul Hu30bd70d2023-02-07 13:20:56 +00001567 break;
Paul Hu019621e2023-01-13 23:26:49 +08001568 default:
1569 return false;
1570 }
1571 return true;
1572 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001573 }
1574 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001575
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001576 @NonNull
1577 private static List<InetAddress> getInetAddresses(@NonNull MdnsServiceInfo serviceInfo) {
1578 final List<String> v4Addrs = serviceInfo.getIpv4Addresses();
1579 final List<String> v6Addrs = serviceInfo.getIpv6Addresses();
1580 final List<InetAddress> addresses = new ArrayList<>(v4Addrs.size() + v6Addrs.size());
1581 for (String ipv4Address : v4Addrs) {
1582 try {
1583 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1584 } catch (IllegalArgumentException e) {
1585 Log.wtf(TAG, "Invalid ipv4 address", e);
1586 }
1587 }
1588 for (String ipv6Address : v6Addrs) {
1589 try {
Yuyang Huanga6a6ff92023-04-24 13:33:34 +09001590 final Inet6Address addr = (Inet6Address) InetAddresses.parseNumericAddress(
1591 ipv6Address);
1592 addresses.add(InetAddressUtils.withScopeId(addr, serviceInfo.getInterfaceIndex()));
1593 } catch (IllegalArgumentException e) {
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001594 Log.wtf(TAG, "Invalid ipv6 address", e);
1595 }
1596 }
1597 return addresses;
1598 }
1599
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001600 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1601 switch (netId) {
1602 case NETID_UNSET:
1603 info.setNetwork(null);
1604 break;
1605 case INetd.LOCAL_NET_ID:
1606 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1607 // visible / usable for apps, so do not return it. Store the interface
1608 // index instead, so at least if the client tries to resolve the service
1609 // with that NsdServiceInfo, it will be done on the same interface.
1610 // If they recreate the NsdServiceInfo themselves, resolution would be
1611 // done on all interfaces as before T, which should also work.
1612 info.setNetwork(null);
1613 info.setInterfaceIndex(ifaceIdx);
1614 break;
1615 default:
1616 info.setNetwork(new Network(netId));
1617 }
1618 }
1619
paulhube186602022-04-12 07:18:23 +00001620 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1621 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1622 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1623 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1624 private String unescape(String s) {
1625 StringBuilder sb = new StringBuilder(s.length());
1626 for (int i = 0; i < s.length(); ++i) {
1627 char c = s.charAt(i);
1628 if (c == '\\') {
1629 if (++i >= s.length()) {
1630 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1631 break;
1632 }
1633 c = s.charAt(i);
1634 if (c != '.' && c != '\\') {
1635 if (i + 2 >= s.length()) {
1636 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1637 break;
1638 }
1639 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1640 + (s.charAt(i + 2) - '0'));
1641 i += 2;
1642 }
1643 }
1644 sb.append(c);
1645 }
1646 return sb.toString();
1647 }
1648
Paul Hu7445e3d2023-03-03 15:14:00 +08001649 /**
1650 * Check the given service type is valid and construct it to a service type
1651 * which can use for discovery / resolution service.
1652 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001653 * <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 +08001654 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1655 * underscore; they are alphanumerical characters or dashes or underscore, except the
1656 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1657 *
Yuyang Huang170d42f2023-12-09 15:26:16 +09001658 * <p>The subtypes may also be specified with a comma after the service type, for example
1659 * _type._tcp,_subtype1,_subtype2
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001660 *
Paul Hu7445e3d2023-03-03 15:14:00 +08001661 * @param serviceType the request service type for discovery / resolution service
1662 * @return constructed service type or null if the given service type is invalid.
1663 */
1664 @Nullable
Yuyang Huang170d42f2023-12-09 15:26:16 +09001665 public static Pair<String, List<String>> parseTypeAndSubtype(String serviceType) {
Paul Hu7445e3d2023-03-03 15:14:00 +08001666 if (TextUtils.isEmpty(serviceType)) return null;
Yuyang Huang86d083f2023-12-12 19:56:41 +09001667 final Pattern serviceTypePattern = Pattern.compile(TYPE_REGEX);
Paul Hu7445e3d2023-03-03 15:14:00 +08001668 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1669 if (!matcher.matches()) return null;
Yuyang Huang170d42f2023-12-09 15:26:16 +09001670 final String queryType = matcher.group(2);
1671 // Use the subtype at the beginning
1672 if (matcher.group(1) != null) {
1673 return new Pair<>(queryType, List.of(matcher.group(1)));
1674 }
1675 // Use the subtypes at the end
1676 final String subTypesStr = matcher.group(3);
1677 if (subTypesStr != null && !subTypesStr.isEmpty()) {
1678 final String[] subTypes = subTypesStr.substring(1).split(",");
1679 return new Pair<>(queryType, List.of(subTypes));
1680 }
1681
1682 return new Pair<>(queryType, Collections.emptyList());
Paul Hu7445e3d2023-03-03 15:14:00 +08001683 }
1684
Kangping Dong5af24b62023-12-10 21:41:16 +08001685 /** Returns {@code true} if {@code subtype} is a valid DNS-SD subtype label. */
1686 private static boolean checkSubtypeLabel(String subtype) {
1687 return Pattern.compile("^" + TYPE_SUBTYPE_LABEL_REGEX + "$").matcher(subtype).matches();
1688 }
1689
Hugo Benichi803a2f02017-04-24 11:35:06 +09001690 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001691 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001692 this(ctx, handler, cleanupDelayMs, new Dependencies());
1693 }
1694
1695 @VisibleForTesting
1696 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001697 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001698 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001699 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001700 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001701 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1702 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001703 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001704
Paul Hu14667de2023-04-17 22:42:47 +08001705 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper(),
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001706 LOGGER.forSubComponent("MdnsSocketProvider"), new SocketRequestMonitor());
Yuyang Huang700778b2023-03-08 16:17:05 +09001707 // Netlink monitor starts on boot, and intentionally never stopped, to ensure that all
Yuyang Huangfca402a2023-05-24 14:45:59 +09001708 // address events are received. When the netlink monitor starts, any IP addresses already
1709 // on the interfaces will not be seen. In practice, the network will not connect at boot
1710 // time As a result, all the netlink message should be observed if the netlink monitor
1711 // starts here.
Yuyang Huang700778b2023-03-08 16:17:05 +09001712 handler.post(mMdnsSocketProvider::startNetLinkMonitor);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001713
1714 // NsdService is started after ActivityManager (startOtherServices in SystemServer, vs.
1715 // startBootstrapServices).
1716 mRunningAppActiveImportanceCutoff = mDeps.getDeviceConfigInt(
1717 MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF,
1718 DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF);
1719 final ActivityManager am = ctx.getSystemService(ActivityManager.class);
1720 am.addOnUidImportanceListener(new UidImportanceListener(handler),
1721 mRunningAppActiveImportanceCutoff);
1722
Paul Huf3fe3332023-10-16 17:13:25 +08001723 final MdnsFeatureFlags flags = new MdnsFeatureFlags.Builder()
1724 .setIsMdnsOffloadFeatureEnabled(mDeps.isTetheringFeatureNotChickenedOut(
1725 mContext, MdnsFeatureFlags.NSD_FORCE_DISABLE_MDNS_OFFLOAD))
1726 .setIncludeInetAddressRecordsInProbing(mDeps.isFeatureEnabled(
1727 mContext, MdnsFeatureFlags.INCLUDE_INET_ADDRESS_RECORDS_IN_PROBING))
Paul Hu596a5002023-10-18 17:07:31 +08001728 .setIsExpiredServicesRemovalEnabled(mDeps.isFeatureEnabled(
1729 mContext, MdnsFeatureFlags.NSD_EXPIRED_SERVICES_REMOVAL))
Paul Hufd357ef2023-11-01 16:32:45 +08001730 .setIsLabelCountLimitEnabled(mDeps.isTetheringFeatureNotChickenedOut(
1731 mContext, MdnsFeatureFlags.NSD_LIMIT_LABEL_COUNT))
Paul Hu01f243f2023-11-22 17:26:36 +08001732 .setIsKnownAnswerSuppressionEnabled(mDeps.isFeatureEnabled(
1733 mContext, MdnsFeatureFlags.NSD_KNOWN_ANSWER_SUPPRESSION))
Paul Huf3fe3332023-10-16 17:13:25 +08001734 .build();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001735 mMdnsSocketClient =
Yuyang Huang7ddf2932023-08-01 18:16:30 +09001736 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider,
Paul Hufd357ef2023-11-01 16:32:45 +08001737 LOGGER.forSubComponent("MdnsMultinetworkSocketClient"), flags);
Paul Hu14667de2023-04-17 22:42:47 +08001738 mMdnsDiscoveryManager = deps.makeMdnsDiscoveryManager(new ExecutorProvider(),
Paul Huf3fe3332023-10-16 17:13:25 +08001739 mMdnsSocketClient, LOGGER.forSubComponent("MdnsDiscoveryManager"), flags);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001740 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1741 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
Yuyang Huangb96a0712023-09-07 15:13:15 +09001742 new AdvertiserCallback(), LOGGER.forSubComponent("MdnsAdvertiser"), flags);
Paul Hu777ed052023-06-19 13:35:15 +00001743 mClock = deps.makeClock();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001744 }
1745
1746 /**
1747 * Dependencies of NsdService, for injection in tests.
1748 */
1749 @VisibleForTesting
1750 public static class Dependencies {
1751 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001752 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001753 *
1754 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001755 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001756 */
1757 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001758 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001759 MDNS_DISCOVERY_MANAGER_VERSION);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001760 }
1761
1762 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001763 * Check whether the MdnsAdvertiser feature is enabled.
1764 *
1765 * @param context The global context information about an app environment.
1766 * @return true if the MdnsAdvertiser feature is enabled.
1767 */
1768 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001769 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001770 MDNS_ADVERTISER_VERSION);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001771 }
1772
1773 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001774 * Get the type allowlist flag value.
1775 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1776 */
1777 @Nullable
1778 public String getTypeAllowlistFlags() {
1779 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1780 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1781 }
1782
1783 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001784 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001785 */
1786 public boolean isFeatureEnabled(Context context, String feature) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001787 return DeviceConfigUtils.isTetheringFeatureEnabled(context, feature);
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001788 }
1789
1790 /**
Yuyang Huangb96a0712023-09-07 15:13:15 +09001791 * @see DeviceConfigUtils#isTetheringFeatureNotChickenedOut
1792 */
Motomu Utsumied4e7ec2023-09-13 14:58:32 +09001793 public boolean isTetheringFeatureNotChickenedOut(Context context, String feature) {
1794 return DeviceConfigUtils.isTetheringFeatureNotChickenedOut(context, feature);
Yuyang Huangb96a0712023-09-07 15:13:15 +09001795 }
1796
1797 /**
Paul Huf3fe3332023-10-16 17:13:25 +08001798 * @see DeviceConfigUtils#isTrunkStableFeatureEnabled
1799 */
1800 public boolean isTrunkStableFeatureEnabled(String feature) {
1801 return DeviceConfigUtils.isTrunkStableFeatureEnabled(feature);
1802 }
1803
1804 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001805 * @see MdnsDiscoveryManager
1806 */
1807 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
Paul Hu14667de2023-04-17 22:42:47 +08001808 @NonNull ExecutorProvider executorProvider,
Paul Huf3fe3332023-10-16 17:13:25 +08001809 @NonNull MdnsMultinetworkSocketClient socketClient, @NonNull SharedLog sharedLog,
1810 @NonNull MdnsFeatureFlags featureFlags) {
1811 return new MdnsDiscoveryManager(
1812 executorProvider, socketClient, sharedLog, featureFlags);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001813 }
1814
1815 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001816 * @see MdnsAdvertiser
1817 */
1818 public MdnsAdvertiser makeMdnsAdvertiser(
1819 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
Yuyang Huangb96a0712023-09-07 15:13:15 +09001820 @NonNull MdnsAdvertiser.AdvertiserCallback cb, @NonNull SharedLog sharedLog,
1821 MdnsFeatureFlags featureFlags) {
1822 return new MdnsAdvertiser(looper, socketProvider, cb, sharedLog, featureFlags);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001823 }
1824
1825 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001826 * @see MdnsSocketProvider
1827 */
Paul Hu14667de2023-04-17 22:42:47 +08001828 public MdnsSocketProvider makeMdnsSocketProvider(@NonNull Context context,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001829 @NonNull Looper looper, @NonNull SharedLog sharedLog,
1830 @NonNull MdnsSocketProvider.SocketRequestMonitor socketCreationCallback) {
1831 return new MdnsSocketProvider(context, looper, sharedLog, socketCreationCallback);
1832 }
1833
1834 /**
1835 * @see DeviceConfig#getInt(String, String, int)
1836 */
1837 public int getDeviceConfigInt(@NonNull String config, int defaultValue) {
1838 return DeviceConfig.getInt(NAMESPACE_TETHERING, config, defaultValue);
1839 }
1840
1841 /**
1842 * @see Binder#getCallingUid()
1843 */
1844 public int getCallingUid() {
1845 return Binder.getCallingUid();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001846 }
Paul Hu777ed052023-06-19 13:35:15 +00001847
1848 /**
1849 * @see NetworkNsdReportedMetrics
1850 */
Paul Hu508a0122023-09-11 15:31:33 +08001851 public NetworkNsdReportedMetrics makeNetworkNsdReportedMetrics(int clientId) {
1852 return new NetworkNsdReportedMetrics(clientId);
Paul Hu777ed052023-06-19 13:35:15 +00001853 }
1854
1855 /**
1856 * @see MdnsUtils.Clock
1857 */
1858 public Clock makeClock() {
1859 return new Clock();
1860 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001861 }
1862
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001863 /**
1864 * Return whether a type is allowlisted to use the Java backend.
1865 * @param type The service type
1866 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1867 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1868 */
1869 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1870 @NonNull String flagPrefix) {
1871 if (type == null) return false;
1872 final String typesConfig = mDeps.getTypeAllowlistFlags();
1873 if (TextUtils.isEmpty(typesConfig)) return false;
1874
1875 final String mappingPrefix = type + ":";
1876 String mappedFlag = null;
1877 for (String mapping : TextUtils.split(typesConfig, ",")) {
1878 if (mapping.startsWith(mappingPrefix)) {
1879 mappedFlag = mapping.substring(mappingPrefix.length());
1880 break;
1881 }
1882 }
1883
1884 if (mappedFlag == null) return false;
1885
1886 return mDeps.isFeatureEnabled(mContext,
1887 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1888 }
1889
1890 private boolean useDiscoveryManagerForType(@Nullable String type) {
1891 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1892 }
1893
1894 private boolean useAdvertiserForType(@Nullable String type) {
1895 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1896 }
1897
paulhu1b35e822022-04-08 14:48:41 +08001898 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001899 HandlerThread thread = new HandlerThread(TAG);
1900 thread.start();
1901 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001902 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001903 return service;
1904 }
1905
paulhu2b9ed952022-02-10 21:58:32 +08001906 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1907 private final StateMachine mStateMachine;
1908
1909 MDnsEventCallback(StateMachine sm) {
1910 mStateMachine = sm;
1911 }
1912
1913 @Override
1914 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1915 mStateMachine.sendMessage(
1916 MDNS_SERVICE_EVENT, status.result, status.id, status);
1917 }
1918
1919 @Override
1920 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1921 mStateMachine.sendMessage(
1922 MDNS_SERVICE_EVENT, status.result, status.id, status);
1923 }
1924
1925 @Override
1926 public void onServiceResolutionStatus(final ResolutionInfo status) {
1927 mStateMachine.sendMessage(
1928 MDNS_SERVICE_EVENT, status.result, status.id, status);
1929 }
1930
1931 @Override
1932 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1933 mStateMachine.sendMessage(
1934 MDNS_SERVICE_EVENT, status.result, status.id, status);
1935 }
1936
1937 @Override
1938 public int getInterfaceVersion() throws RemoteException {
1939 return this.VERSION;
1940 }
1941
1942 @Override
1943 public String getInterfaceHash() throws RemoteException {
1944 return this.HASH;
1945 }
1946 }
1947
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001948 private void sendAllOffloadServiceInfos(@NonNull OffloadEngineInfo offloadEngineInfo) {
1949 final String targetInterface = offloadEngineInfo.mInterfaceName;
1950 final IOffloadEngine offloadEngine = offloadEngineInfo.mOffloadEngine;
1951 final List<MdnsAdvertiser.OffloadServiceInfoWrapper> offloadWrappers =
1952 mAdvertiser.getAllInterfaceOffloadServiceInfos(targetInterface);
1953 for (MdnsAdvertiser.OffloadServiceInfoWrapper wrapper : offloadWrappers) {
1954 try {
1955 offloadEngine.onOffloadServiceUpdated(wrapper.mOffloadServiceInfo);
1956 } catch (RemoteException e) {
1957 // Can happen in regular cases, do not log a stacktrace
1958 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
1959 }
1960 }
1961 }
1962
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001963 private void sendOffloadServiceInfosUpdate(@NonNull String targetInterfaceName,
1964 @NonNull OffloadServiceInfo offloadServiceInfo, boolean isRemove) {
1965 final int count = mOffloadEngines.beginBroadcast();
1966 try {
1967 for (int i = 0; i < count; i++) {
1968 final OffloadEngineInfo offloadEngineInfo =
1969 (OffloadEngineInfo) mOffloadEngines.getBroadcastCookie(i);
1970 final String interfaceName = offloadEngineInfo.mInterfaceName;
1971 if (!targetInterfaceName.equals(interfaceName)
1972 || ((offloadEngineInfo.mOffloadType
1973 & offloadServiceInfo.getOffloadType()) == 0)) {
1974 continue;
1975 }
1976 try {
1977 if (isRemove) {
1978 mOffloadEngines.getBroadcastItem(i).onOffloadServiceRemoved(
1979 offloadServiceInfo);
1980 } else {
1981 mOffloadEngines.getBroadcastItem(i).onOffloadServiceUpdated(
1982 offloadServiceInfo);
1983 }
1984 } catch (RemoteException e) {
1985 // Can happen in regular cases, do not log a stacktrace
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001986 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001987 }
1988 }
1989 } finally {
1990 mOffloadEngines.finishBroadcast();
1991 }
1992 }
1993
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001994 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001995 // TODO: add a callback to notify when a service is being added on each interface (as soon
1996 // as probing starts), and call mOffloadCallbacks. This callback is for
1997 // OFFLOAD_CAPABILITY_FILTER_REPLIES offload type.
1998
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001999 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00002000 public void onRegisterServiceSucceeded(int transactionId, NsdServiceInfo registeredInfo) {
2001 mServiceLogs.log("onRegisterServiceSucceeded: transactionId " + transactionId);
2002 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002003 if (clientInfo == null) return;
2004
Paul Hud44e1b72023-06-16 02:07:42 +00002005 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
2006 if (clientRequestId < 0) return;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002007
2008 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
2009 // historical behavior.
2010 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
Paul Hu777ed052023-06-19 13:35:15 +00002011 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu508a0122023-09-11 15:31:33 +08002012 clientInfo.onRegisterServiceSucceeded(clientRequestId, cbInfo, request);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002013 }
2014
2015 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00002016 public void onRegisterServiceFailed(int transactionId, int errorCode) {
2017 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002018 if (clientInfo == null) return;
2019
Paul Hud44e1b72023-06-16 02:07:42 +00002020 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
2021 if (clientRequestId < 0) return;
Paul Hu777ed052023-06-19 13:35:15 +00002022 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu508a0122023-09-11 15:31:33 +08002023 clientInfo.onRegisterServiceFailed(clientRequestId, errorCode, false /* isLegacy */,
2024 transactionId, request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002025 }
2026
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002027 @Override
2028 public void onOffloadStartOrUpdate(@NonNull String interfaceName,
2029 @NonNull OffloadServiceInfo offloadServiceInfo) {
2030 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, false /* isRemove */);
2031 }
2032
2033 @Override
2034 public void onOffloadStop(@NonNull String interfaceName,
2035 @NonNull OffloadServiceInfo offloadServiceInfo) {
2036 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, true /* isRemove */);
2037 }
2038
Paul Hud44e1b72023-06-16 02:07:42 +00002039 private ClientInfo getClientInfoOrLog(int transactionId) {
2040 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002041 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00002042 Log.e(TAG, String.format("Callback for service %d has no client", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002043 }
2044 return clientInfo;
2045 }
2046
Paul Hud44e1b72023-06-16 02:07:42 +00002047 private int getClientRequestIdOrLog(@NonNull ClientInfo info, int transactionId) {
2048 final int clientRequestId = info.getClientRequestId(transactionId);
2049 if (clientRequestId < 0) {
2050 Log.e(TAG, String.format(
2051 "Client request ID not found for service %d", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002052 }
Paul Hud44e1b72023-06-16 02:07:42 +00002053 return clientRequestId;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002054 }
2055 }
2056
Paul Hu2e0a88c2023-03-09 16:05:01 +08002057 private static class ConnectorArgs {
2058 @NonNull public final NsdServiceConnector connector;
2059 @NonNull public final INsdManagerCallback callback;
2060 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002061 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002062
2063 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00002064 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08002065 this.connector = connector;
2066 this.callback = callback;
2067 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002068 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002069 }
2070 }
2071
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002072 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08002073 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09002074 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu101dbf52023-08-09 16:05:20 +08002075 final int uid = mDeps.getCallingUid();
2076 if (cb == null) {
2077 throw new IllegalArgumentException("Unknown client callback from uid=" + uid);
2078 }
Paul Hu2e0a88c2023-03-09 16:05:01 +08002079 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002080 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00002081 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
Paul Hu101dbf52023-08-09 16:05:20 +08002082 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend, uid)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002083 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07002084 }
2085
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002086 private static class ListenerArgs {
2087 public final NsdServiceConnector connector;
2088 public final NsdServiceInfo serviceInfo;
2089 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
2090 this.connector = connector;
2091 this.serviceInfo = serviceInfo;
2092 }
2093 }
2094
Yuyang Huang86d083f2023-12-12 19:56:41 +09002095 private static class AdvertisingArgs {
2096 public final NsdServiceConnector connector;
2097 public final AdvertisingRequest advertisingRequest;
2098
2099 AdvertisingArgs(NsdServiceConnector connector, AdvertisingRequest advertisingRequest) {
2100 this.connector = connector;
2101 this.advertisingRequest = advertisingRequest;
2102 }
2103 }
2104
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002105 private class NsdServiceConnector extends INsdServiceConnector.Stub
2106 implements IBinder.DeathRecipient {
Yuyang Huang86d083f2023-12-12 19:56:41 +09002107
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002108 @Override
Yuyang Huang86d083f2023-12-12 19:56:41 +09002109 public void registerService(int listenerKey, AdvertisingRequest advertisingRequest)
2110 throws RemoteException {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002111 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2112 NsdManager.REGISTER_SERVICE, 0, listenerKey,
Yuyang Huang86d083f2023-12-12 19:56:41 +09002113 new AdvertisingArgs(this, advertisingRequest)
2114 ));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002115 }
2116
2117 @Override
2118 public void unregisterService(int listenerKey) {
2119 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2120 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
Yuyang Huang86d083f2023-12-12 19:56:41 +09002121 new ListenerArgs(this, (NsdServiceInfo) null)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002122 }
2123
2124 @Override
2125 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
2126 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2127 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
2128 new ListenerArgs(this, serviceInfo)));
2129 }
2130
2131 @Override
2132 public void stopDiscovery(int listenerKey) {
Yuyang Huang86d083f2023-12-12 19:56:41 +09002133 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.STOP_DISCOVERY,
2134 0, listenerKey, new ListenerArgs(this, (NsdServiceInfo) null)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002135 }
2136
2137 @Override
2138 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
2139 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2140 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
2141 new ListenerArgs(this, serviceInfo)));
2142 }
2143
2144 @Override
Paul Hub58deb72022-12-26 09:24:42 +00002145 public void stopResolution(int listenerKey) {
Yuyang Huang86d083f2023-12-12 19:56:41 +09002146 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.STOP_RESOLUTION,
2147 0, listenerKey, new ListenerArgs(this, (NsdServiceInfo) null)));
Paul Hub58deb72022-12-26 09:24:42 +00002148 }
2149
2150 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00002151 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
2152 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2153 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
2154 new ListenerArgs(this, serviceInfo)));
2155 }
2156
2157 @Override
2158 public void unregisterServiceInfoCallback(int listenerKey) {
2159 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2160 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
Yuyang Huang86d083f2023-12-12 19:56:41 +09002161 new ListenerArgs(this, (NsdServiceInfo) null)));
Paul Hu18aeccc2022-12-27 08:48:48 +00002162 }
2163
2164 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002165 public void startDaemon() {
Yuyang Huang86d083f2023-12-12 19:56:41 +09002166 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.DAEMON_STARTUP,
2167 new ListenerArgs(this, (NsdServiceInfo) null)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002168 }
2169
2170 @Override
2171 public void binderDied() {
2172 mNsdStateMachine.sendMessage(
2173 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002174
2175 }
2176
2177 @Override
2178 public void registerOffloadEngine(String ifaceName, IOffloadEngine cb,
2179 @OffloadEngine.OffloadCapability long offloadCapabilities,
2180 @OffloadEngine.OffloadType long offloadTypes) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002181 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002182 Objects.requireNonNull(ifaceName);
2183 Objects.requireNonNull(cb);
2184 mNsdStateMachine.sendMessage(
2185 mNsdStateMachine.obtainMessage(NsdManager.REGISTER_OFFLOAD_ENGINE,
2186 new OffloadEngineInfo(cb, ifaceName, offloadCapabilities,
2187 offloadTypes)));
2188 }
2189
2190 @Override
2191 public void unregisterOffloadEngine(IOffloadEngine cb) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002192 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002193 Objects.requireNonNull(cb);
2194 mNsdStateMachine.sendMessage(
2195 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_OFFLOAD_ENGINE, cb));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002196 }
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002197
2198 private static void checkOffloadEnginePermission(Context context) {
2199 if (!SdkLevel.isAtLeastT()) {
2200 throw new SecurityException("API is not available in before API level 33");
2201 }
Yuyang Huangd5896e72023-11-28 13:23:59 +09002202
Ken Chena7bae552023-12-27 11:40:57 +08002203 final ArrayList<String> permissionsList = new ArrayList<>(Arrays.asList(NETWORK_STACK,
2204 PERMISSION_MAINLINE_NETWORK_STACK, NETWORK_SETTINGS));
2205
2206 if (SdkLevel.isAtLeastV()) {
2207 // REGISTER_NSD_OFFLOAD_ENGINE was only added to the SDK in V.
2208 permissionsList.add(REGISTER_NSD_OFFLOAD_ENGINE);
2209 } else if (SdkLevel.isAtLeastU()) {
2210 // REGISTER_NSD_OFFLOAD_ENGINE cannot be backport to U. In U, check the DEVICE_POWER
2211 // permission instead.
2212 permissionsList.add(DEVICE_POWER);
Yuyang Huangd5896e72023-11-28 13:23:59 +09002213 }
2214
Ken Chena7bae552023-12-27 11:40:57 +08002215 if (PermissionUtils.checkAnyPermissionOf(context,
2216 permissionsList.toArray(new String[0]))) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002217 return;
2218 }
2219 throw new SecurityException("Requires one of the following permissions: "
Ken Chena7bae552023-12-27 11:40:57 +08002220 + String.join(", ", permissionsList) + ".");
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002221 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002222 }
2223
Hugo Benichi912db992017-04-24 16:41:03 +09002224 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07002225 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07002226 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09002227 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
2228 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07002229 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07002230 }
2231
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002232 private int getUniqueId() {
2233 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
2234 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002235 }
2236
Paul Hud44e1b72023-06-16 02:07:42 +00002237 private boolean registerService(int transactionId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09002238 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002239 Log.d(TAG, "registerService: " + transactionId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002240 }
Hugo Benichi6d706442017-04-24 16:19:58 +09002241 String name = service.getServiceName();
2242 String type = service.getServiceType();
2243 int port = service.getPort();
2244 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002245 final int registerInterface = getNetworkInterfaceIndex(service);
2246 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08002247 Log.e(TAG, "Interface to register service on not found");
2248 return false;
2249 }
Paul Hud44e1b72023-06-16 02:07:42 +00002250 return mMDnsManager.registerService(
2251 transactionId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002252 }
2253
Paul Hud44e1b72023-06-16 02:07:42 +00002254 private boolean unregisterService(int transactionId) {
2255 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002256 }
2257
Paul Hud44e1b72023-06-16 02:07:42 +00002258 private boolean discoverServices(int transactionId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08002259 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002260 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
2261 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002262 Log.e(TAG, "Interface to discover service on not found");
2263 return false;
2264 }
Paul Hud44e1b72023-06-16 02:07:42 +00002265 return mMDnsManager.discover(transactionId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002266 }
2267
Paul Hud44e1b72023-06-16 02:07:42 +00002268 private boolean stopServiceDiscovery(int transactionId) {
2269 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002270 }
2271
Paul Hud44e1b72023-06-16 02:07:42 +00002272 private boolean resolveService(int transactionId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002273 final String name = service.getServiceName();
2274 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002275 final int resolveInterface = getNetworkInterfaceIndex(service);
2276 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002277 Log.e(TAG, "Interface to resolve service on not found");
2278 return false;
2279 }
Paul Hud44e1b72023-06-16 02:07:42 +00002280 return mMDnsManager.resolve(transactionId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002281 }
2282
2283 /**
2284 * Guess the interface to use to resolve or discover a service on a specific network.
2285 *
2286 * This is an imperfect guess, as for example the network may be gone or not yet fully
2287 * registered. This is fine as failing is correct if the network is gone, and a client
2288 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
2289 * this is to support the legacy mdnsresponder implementation, which historically resolved
2290 * services on an unspecified network.
2291 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002292 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
2293 final Network network = serviceInfo.getNetwork();
2294 if (network == null) {
2295 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
2296 // provided by NsdService from discovery results, and the service was found on an
2297 // interface that has no app-usable Network).
2298 if (serviceInfo.getInterfaceIndex() != 0) {
2299 return serviceInfo.getInterfaceIndex();
2300 }
2301 return IFACE_IDX_ANY;
2302 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002303
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002304 String interfaceName = getNetworkInterfaceName(network);
2305 if (interfaceName == null) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002306 return IFACE_IDX_ANY;
2307 }
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002308 return getNetworkInterfaceIndexByName(interfaceName);
2309 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002310
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002311 private String getNetworkInterfaceName(@Nullable Network network) {
2312 if (network == null) {
2313 return null;
2314 }
2315 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
2316 if (cm == null) {
2317 Log.wtf(TAG, "No ConnectivityManager");
2318 return null;
2319 }
2320 final LinkProperties lp = cm.getLinkProperties(network);
2321 if (lp == null) {
2322 return null;
2323 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002324 // Only resolve on non-stacked interfaces
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002325 return lp.getInterfaceName();
2326 }
2327
2328 private int getNetworkInterfaceIndexByName(final String ifaceName) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002329 final NetworkInterface iface;
2330 try {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002331 iface = NetworkInterface.getByName(ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002332 } catch (SocketException e) {
2333 Log.e(TAG, "Error querying interface", e);
2334 return IFACE_IDX_ANY;
2335 }
2336
2337 if (iface == null) {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002338 Log.e(TAG, "Interface not found: " + ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002339 return IFACE_IDX_ANY;
2340 }
2341
2342 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002343 }
2344
Paul Hud44e1b72023-06-16 02:07:42 +00002345 private boolean stopResolveService(int transactionId) {
2346 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002347 }
2348
Paul Hud44e1b72023-06-16 02:07:42 +00002349 private boolean getAddrInfo(int transactionId, String hostname, int interfaceIdx) {
2350 return mMDnsManager.getServiceAddress(transactionId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002351 }
2352
Paul Hud44e1b72023-06-16 02:07:42 +00002353 private boolean stopGetAddrInfo(int transactionId) {
2354 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002355 }
2356
2357 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00002358 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2359 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002360
Paul Hub2e67d32023-04-18 05:50:14 +00002361 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2362 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07002363 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00002364
2365 // Dump service and clients logs
2366 pw.println();
Paul Hu14667de2023-04-17 22:42:47 +08002367 pw.println("Logs:");
Paul Hub2e67d32023-04-18 05:50:14 +00002368 pw.increaseIndent();
2369 mServiceLogs.reverseDump(pw);
2370 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002371 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002372
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002373 private abstract static class ClientRequest {
Paul Hud44e1b72023-06-16 02:07:42 +00002374 private final int mTransactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002375 private final long mStartTimeMs;
Paul Hu812e9212023-06-20 06:24:53 +00002376 private int mFoundServiceCount = 0;
2377 private int mLostServiceCount = 0;
2378 private final Set<String> mServices = new ArraySet<>();
Paul Hua6bc4632023-06-26 01:18:29 +00002379 private boolean mIsServiceFromCache = false;
Paul Hubad6fe92023-07-24 21:25:22 +08002380 private int mSentQueryCount = NO_SENT_QUERY_COUNT;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002381
Paul Hu812e9212023-06-20 06:24:53 +00002382 private ClientRequest(int transactionId, long startTimeMs) {
Paul Hud44e1b72023-06-16 02:07:42 +00002383 mTransactionId = transactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002384 mStartTimeMs = startTimeMs;
2385 }
2386
Paul Hu812e9212023-06-20 06:24:53 +00002387 public long calculateRequestDurationMs(long stopTimeMs) {
Paul Hu777ed052023-06-19 13:35:15 +00002388 return stopTimeMs - mStartTimeMs;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002389 }
Paul Hu812e9212023-06-20 06:24:53 +00002390
2391 public void onServiceFound(String serviceName) {
2392 mFoundServiceCount++;
2393 if (mServices.size() <= MAX_SERVICES_COUNT_METRIC_PER_CLIENT) {
2394 mServices.add(serviceName);
2395 }
2396 }
2397
2398 public void onServiceLost() {
2399 mLostServiceCount++;
2400 }
2401
2402 public int getFoundServiceCount() {
2403 return mFoundServiceCount;
2404 }
2405
2406 public int getLostServiceCount() {
2407 return mLostServiceCount;
2408 }
2409
2410 public int getServicesCount() {
2411 return mServices.size();
2412 }
Paul Hua6bc4632023-06-26 01:18:29 +00002413
2414 public void setServiceFromCache(boolean isServiceFromCache) {
2415 mIsServiceFromCache = isServiceFromCache;
2416 }
2417
2418 public boolean isServiceFromCache() {
2419 return mIsServiceFromCache;
2420 }
Paul Hubad6fe92023-07-24 21:25:22 +08002421
2422 public void onQuerySent() {
2423 mSentQueryCount++;
2424 }
2425
2426 public int getSentQueryCount() {
2427 return mSentQueryCount;
2428 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002429 }
2430
2431 private static class LegacyClientRequest extends ClientRequest {
2432 private final int mRequestCode;
2433
Paul Hu812e9212023-06-20 06:24:53 +00002434 private LegacyClientRequest(int transactionId, int requestCode, long startTimeMs) {
2435 super(transactionId, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002436 mRequestCode = requestCode;
2437 }
2438 }
2439
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002440 private abstract static class JavaBackendClientRequest extends ClientRequest {
2441 @Nullable
2442 private final Network mRequestedNetwork;
2443
Paul Hu777ed052023-06-19 13:35:15 +00002444 private JavaBackendClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002445 long startTimeMs) {
2446 super(transactionId, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002447 mRequestedNetwork = requestedNetwork;
2448 }
2449
2450 @Nullable
2451 public Network getRequestedNetwork() {
2452 return mRequestedNetwork;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002453 }
2454 }
2455
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002456 private static class AdvertiserClientRequest extends JavaBackendClientRequest {
Paul Hu777ed052023-06-19 13:35:15 +00002457 private AdvertiserClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002458 long startTimeMs) {
2459 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002460 }
2461 }
2462
2463 private static class DiscoveryManagerRequest extends JavaBackendClientRequest {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002464 @NonNull
2465 private final MdnsListener mListener;
2466
Paul Hud44e1b72023-06-16 02:07:42 +00002467 private DiscoveryManagerRequest(int transactionId, @NonNull MdnsListener listener,
Paul Hu812e9212023-06-20 06:24:53 +00002468 @Nullable Network requestedNetwork, long startTimeMs) {
2469 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002470 mListener = listener;
2471 }
2472 }
2473
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002474 /* Information tracked per client */
2475 private class ClientInfo {
2476
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002477 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002478 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002479 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002480 private NsdServiceInfo mResolvedService;
2481
Paul Hud44e1b72023-06-16 02:07:42 +00002482 /* A map from client request ID (listenerKey) to the request */
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002483 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08002484
Luke Huangf7277ed2021-07-12 21:15:10 +08002485 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002486 private boolean mIsPreSClient = false;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002487 private final int mUid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002488 // The flag of using java backend if the client's target SDK >= U
2489 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002490 // Store client logs
2491 private final SharedLog mClientLogs;
Paul Hucdef3532023-06-18 14:47:35 +00002492 // Report the nsd metrics data
2493 private final NetworkNsdReportedMetrics mMetrics;
Luke Huangf7277ed2021-07-12 21:15:10 +08002494
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002495 private ClientInfo(INsdManagerCallback cb, int uid, boolean useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +00002496 SharedLog sharedLog, NetworkNsdReportedMetrics metrics) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002497 mCb = cb;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002498 mUid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002499 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002500 mClientLogs = sharedLog;
2501 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Paul Hucdef3532023-06-18 14:47:35 +00002502 mMetrics = metrics;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002503 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002504
2505 @Override
2506 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06002507 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07002508 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002509 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002510 sb.append("mUseJavaBackend ").append(mUseJavaBackend).append("\n");
2511 sb.append("mUid ").append(mUid).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002512 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002513 int clientRequestId = mClientRequests.keyAt(i);
2514 sb.append("clientRequestId ")
2515 .append(clientRequestId)
2516 .append(" transactionId ").append(mClientRequests.valueAt(i).mTransactionId)
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002517 .append(" type ").append(
2518 mClientRequests.valueAt(i).getClass().getSimpleName())
2519 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07002520 }
2521 return sb.toString();
2522 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002523
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002524 private boolean isPreSClient() {
2525 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08002526 }
2527
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002528 private void setPreSClient() {
2529 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08002530 }
2531
Paul Hu812e9212023-06-20 06:24:53 +00002532 private MdnsListener unregisterMdnsListenerFromRequest(ClientRequest request) {
Paul Hue4f5f252023-02-16 21:13:47 +08002533 final MdnsListener listener =
2534 ((DiscoveryManagerRequest) request).mListener;
2535 mMdnsDiscoveryManager.unregisterListener(
2536 listener.getListenedServiceType(), listener);
Paul Hu812e9212023-06-20 06:24:53 +00002537 return listener;
Paul Hue4f5f252023-02-16 21:13:47 +08002538 }
2539
Dave Plattfeff2af2014-03-07 14:48:22 -08002540 // Remove any pending requests from the global map when we get rid of a client,
2541 // and send cancellations to the daemon.
2542 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00002543 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09002544 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002545 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002546 final int clientRequestId = mClientRequests.keyAt(i);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002547 final ClientRequest request = mClientRequests.valueAt(i);
Paul Hud44e1b72023-06-16 02:07:42 +00002548 final int transactionId = request.mTransactionId;
2549 mTransactionIdToClientInfoMap.remove(transactionId);
paulhub2225702021-11-17 09:35:33 +08002550 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002551 Log.d(TAG, "Terminating clientRequestId " + clientRequestId
2552 + " transactionId " + transactionId
2553 + " type " + mClientRequests.get(clientRequestId));
paulhub2225702021-11-17 09:35:33 +08002554 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002555
2556 if (request instanceof DiscoveryManagerRequest) {
Paul Hu812e9212023-06-20 06:24:53 +00002557 final MdnsListener listener = unregisterMdnsListenerFromRequest(request);
2558 if (listener instanceof DiscoveryListener) {
Paul Hu508a0122023-09-11 15:31:33 +08002559 mMetrics.reportServiceDiscoveryStop(false /* isLegacy */, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00002560 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2561 request.getFoundServiceCount(),
2562 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002563 request.getServicesCount(),
2564 request.getSentQueryCount());
Paul Hu60149052023-07-31 14:26:08 +08002565 } else if (listener instanceof ResolutionListener) {
Paul Hu508a0122023-09-11 15:31:33 +08002566 mMetrics.reportServiceResolutionStop(false /* isLegacy */, transactionId,
Paul Hu60149052023-07-31 14:26:08 +08002567 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Huddce5912023-08-01 10:26:49 +08002568 } else if (listener instanceof ServiceInfoListener) {
2569 mMetrics.reportServiceInfoCallbackUnregistered(transactionId,
2570 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2571 request.getFoundServiceCount(),
2572 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002573 request.isServiceFromCache(),
2574 request.getSentQueryCount());
Paul Hu812e9212023-06-20 06:24:53 +00002575 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002576 continue;
2577 }
2578
2579 if (request instanceof AdvertiserClientRequest) {
Paul Hu043bcd42023-07-14 16:38:25 +08002580 final AdvertiserMetrics metrics =
2581 mAdvertiser.getAdvertiserMetrics(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00002582 mAdvertiser.removeService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002583 mMetrics.reportServiceUnregistration(false /* isLegacy */, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002584 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2585 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2586 metrics.mConflictDuringProbingCount,
2587 metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002588 continue;
2589 }
2590
2591 if (!(request instanceof LegacyClientRequest)) {
2592 throw new IllegalStateException("Unknown request type: " + request.getClass());
2593 }
2594
2595 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08002596 case NsdManager.DISCOVER_SERVICES:
Paul Hud44e1b72023-06-16 02:07:42 +00002597 stopServiceDiscovery(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002598 mMetrics.reportServiceDiscoveryStop(true /* isLegacy */, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00002599 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2600 request.getFoundServiceCount(),
2601 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002602 request.getServicesCount(),
2603 NO_SENT_QUERY_COUNT);
Dave Plattfeff2af2014-03-07 14:48:22 -08002604 break;
2605 case NsdManager.RESOLVE_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002606 stopResolveService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002607 mMetrics.reportServiceResolutionStop(true /* isLegacy */, transactionId,
Paul Hu60149052023-07-31 14:26:08 +08002608 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Dave Plattfeff2af2014-03-07 14:48:22 -08002609 break;
2610 case NsdManager.REGISTER_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002611 unregisterService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002612 mMetrics.reportServiceUnregistration(true /* isLegacy */, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002613 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2614 NO_PACKET /* repliedRequestsCount */,
2615 NO_PACKET /* sentPacketCount */,
2616 0 /* conflictDuringProbingCount */,
2617 0 /* conflictAfterProbingCount */);
Dave Plattfeff2af2014-03-07 14:48:22 -08002618 break;
2619 default:
2620 break;
2621 }
2622 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002623 mClientRequests.clear();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002624 updateMulticastLock();
2625 }
2626
2627 /**
2628 * Returns true if this client has any Java backend request that requests one of the given
2629 * networks.
2630 */
2631 boolean hasAnyJavaBackendRequestForNetworks(@NonNull ArraySet<Network> networks) {
2632 for (int i = 0; i < mClientRequests.size(); i++) {
2633 final ClientRequest req = mClientRequests.valueAt(i);
2634 if (!(req instanceof JavaBackendClientRequest)) {
2635 continue;
2636 }
2637 final Network reqNetwork = ((JavaBackendClientRequest) mClientRequests.valueAt(i))
2638 .getRequestedNetwork();
2639 if (MdnsUtils.isAnyNetworkMatched(reqNetwork, networks)) {
2640 return true;
2641 }
2642 }
2643 return false;
Dave Plattfeff2af2014-03-07 14:48:22 -08002644 }
2645
Paul Hud44e1b72023-06-16 02:07:42 +00002646 // mClientRequests is a sparse array of client request id -> ClientRequest. For a given
2647 // transaction id, return the corresponding client request id.
2648 private int getClientRequestId(final int transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002649 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002650 if (mClientRequests.valueAt(i).mTransactionId == transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002651 return mClientRequests.keyAt(i);
2652 }
Christopher Lane74411222014-04-25 18:39:07 -07002653 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002654 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07002655 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002656
Paul Hub2e67d32023-04-18 05:50:14 +00002657 private void log(String message) {
2658 mClientLogs.log(message);
2659 }
2660
Paul Hu508a0122023-09-11 15:31:33 +08002661 private static boolean isLegacyClientRequest(@NonNull ClientRequest request) {
2662 return !(request instanceof DiscoveryManagerRequest)
2663 && !(request instanceof AdvertiserClientRequest);
2664 }
2665
2666 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info,
2667 ClientRequest request) {
2668 mMetrics.reportServiceDiscoveryStarted(
2669 isLegacyClientRequest(request), request.mTransactionId);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002670 try {
2671 mCb.onDiscoverServicesStarted(listenerKey, info);
2672 } catch (RemoteException e) {
2673 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
2674 }
2675 }
Paul Hu508a0122023-09-11 15:31:33 +08002676 void onDiscoverServicesFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2677 onDiscoverServicesFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2678 0L /* durationMs */);
Paul Hu812e9212023-06-20 06:24:53 +00002679 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002680
Paul Hu508a0122023-09-11 15:31:33 +08002681 void onDiscoverServicesFailed(int listenerKey, int error, boolean isLegacy,
2682 int transactionId, long durationMs) {
2683 mMetrics.reportServiceDiscoveryFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002684 try {
2685 mCb.onDiscoverServicesFailed(listenerKey, error);
2686 } catch (RemoteException e) {
2687 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
2688 }
2689 }
2690
Paul Hu812e9212023-06-20 06:24:53 +00002691 void onServiceFound(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2692 request.onServiceFound(info.getServiceName());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002693 try {
2694 mCb.onServiceFound(listenerKey, info);
2695 } catch (RemoteException e) {
2696 Log.e(TAG, "Error calling onServiceFound(", e);
2697 }
2698 }
2699
Paul Hu812e9212023-06-20 06:24:53 +00002700 void onServiceLost(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2701 request.onServiceLost();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002702 try {
2703 mCb.onServiceLost(listenerKey, info);
2704 } catch (RemoteException e) {
2705 Log.e(TAG, "Error calling onServiceLost(", e);
2706 }
2707 }
2708
2709 void onStopDiscoveryFailed(int listenerKey, int error) {
2710 try {
2711 mCb.onStopDiscoveryFailed(listenerKey, error);
2712 } catch (RemoteException e) {
2713 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
2714 }
2715 }
2716
Paul Hu812e9212023-06-20 06:24:53 +00002717 void onStopDiscoverySucceeded(int listenerKey, ClientRequest request) {
2718 mMetrics.reportServiceDiscoveryStop(
Paul Hu508a0122023-09-11 15:31:33 +08002719 isLegacyClientRequest(request),
Paul Hu812e9212023-06-20 06:24:53 +00002720 request.mTransactionId,
2721 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2722 request.getFoundServiceCount(),
2723 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002724 request.getServicesCount(),
2725 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002726 try {
2727 mCb.onStopDiscoverySucceeded(listenerKey);
2728 } catch (RemoteException e) {
2729 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2730 }
2731 }
2732
Paul Hu508a0122023-09-11 15:31:33 +08002733 void onRegisterServiceFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2734 onRegisterServiceFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2735 0L /* durationMs */);
Paul Hu777ed052023-06-19 13:35:15 +00002736 }
2737
Paul Hu508a0122023-09-11 15:31:33 +08002738 void onRegisterServiceFailed(int listenerKey, int error, boolean isLegacy,
2739 int transactionId, long durationMs) {
2740 mMetrics.reportServiceRegistrationFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002741 try {
2742 mCb.onRegisterServiceFailed(listenerKey, error);
2743 } catch (RemoteException e) {
2744 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2745 }
2746 }
2747
Paul Hu508a0122023-09-11 15:31:33 +08002748 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info,
2749 ClientRequest request) {
2750 mMetrics.reportServiceRegistrationSucceeded(isLegacyClientRequest(request),
2751 request.mTransactionId,
2752 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002753 try {
2754 mCb.onRegisterServiceSucceeded(listenerKey, info);
2755 } catch (RemoteException e) {
2756 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2757 }
2758 }
2759
2760 void onUnregisterServiceFailed(int listenerKey, int error) {
2761 try {
2762 mCb.onUnregisterServiceFailed(listenerKey, error);
2763 } catch (RemoteException e) {
2764 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2765 }
2766 }
2767
Paul Hu508a0122023-09-11 15:31:33 +08002768 void onUnregisterServiceSucceeded(int listenerKey, ClientRequest request,
Paul Hu043bcd42023-07-14 16:38:25 +08002769 AdvertiserMetrics metrics) {
Paul Hu508a0122023-09-11 15:31:33 +08002770 mMetrics.reportServiceUnregistration(isLegacyClientRequest(request),
2771 request.mTransactionId,
2772 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hu043bcd42023-07-14 16:38:25 +08002773 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2774 metrics.mConflictDuringProbingCount, metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002775 try {
2776 mCb.onUnregisterServiceSucceeded(listenerKey);
2777 } catch (RemoteException e) {
2778 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2779 }
2780 }
2781
Paul Hu508a0122023-09-11 15:31:33 +08002782 void onResolveServiceFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2783 onResolveServiceFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2784 0L /* durationMs */);
Paul Hua6bc4632023-06-26 01:18:29 +00002785 }
2786
Paul Hu508a0122023-09-11 15:31:33 +08002787 void onResolveServiceFailed(int listenerKey, int error, boolean isLegacy,
2788 int transactionId, long durationMs) {
2789 mMetrics.reportServiceResolutionFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002790 try {
2791 mCb.onResolveServiceFailed(listenerKey, error);
2792 } catch (RemoteException e) {
2793 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2794 }
2795 }
2796
Paul Hua6bc4632023-06-26 01:18:29 +00002797 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info,
2798 ClientRequest request) {
2799 mMetrics.reportServiceResolved(
Paul Hu508a0122023-09-11 15:31:33 +08002800 isLegacyClientRequest(request),
Paul Hua6bc4632023-06-26 01:18:29 +00002801 request.mTransactionId,
2802 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hubad6fe92023-07-24 21:25:22 +08002803 request.isServiceFromCache(),
2804 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002805 try {
2806 mCb.onResolveServiceSucceeded(listenerKey, info);
2807 } catch (RemoteException e) {
2808 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2809 }
2810 }
Paul Hub58deb72022-12-26 09:24:42 +00002811
2812 void onStopResolutionFailed(int listenerKey, int error) {
2813 try {
2814 mCb.onStopResolutionFailed(listenerKey, error);
2815 } catch (RemoteException e) {
2816 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2817 }
2818 }
2819
Paul Hu60149052023-07-31 14:26:08 +08002820 void onStopResolutionSucceeded(int listenerKey, ClientRequest request) {
2821 mMetrics.reportServiceResolutionStop(
Paul Hu508a0122023-09-11 15:31:33 +08002822 isLegacyClientRequest(request),
Paul Hu60149052023-07-31 14:26:08 +08002823 request.mTransactionId,
2824 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hub58deb72022-12-26 09:24:42 +00002825 try {
2826 mCb.onStopResolutionSucceeded(listenerKey);
2827 } catch (RemoteException e) {
2828 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2829 }
2830 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002831
2832 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
Paul Huddce5912023-08-01 10:26:49 +08002833 mMetrics.reportServiceInfoCallbackRegistrationFailed(NO_TRANSACTION);
Paul Hu18aeccc2022-12-27 08:48:48 +00002834 try {
2835 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2836 } catch (RemoteException e) {
2837 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2838 }
2839 }
2840
Paul Huddce5912023-08-01 10:26:49 +08002841 void onServiceInfoCallbackRegistered(int transactionId) {
2842 mMetrics.reportServiceInfoCallbackRegistered(transactionId);
2843 }
2844
2845 void onServiceUpdated(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2846 request.onServiceFound(info.getServiceName());
Paul Hu18aeccc2022-12-27 08:48:48 +00002847 try {
2848 mCb.onServiceUpdated(listenerKey, info);
2849 } catch (RemoteException e) {
2850 Log.e(TAG, "Error calling onServiceUpdated", e);
2851 }
2852 }
2853
Paul Huddce5912023-08-01 10:26:49 +08002854 void onServiceUpdatedLost(int listenerKey, ClientRequest request) {
2855 request.onServiceLost();
Paul Hu18aeccc2022-12-27 08:48:48 +00002856 try {
2857 mCb.onServiceUpdatedLost(listenerKey);
2858 } catch (RemoteException e) {
2859 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2860 }
2861 }
2862
Paul Huddce5912023-08-01 10:26:49 +08002863 void onServiceInfoCallbackUnregistered(int listenerKey, ClientRequest request) {
2864 mMetrics.reportServiceInfoCallbackUnregistered(
2865 request.mTransactionId,
2866 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2867 request.getFoundServiceCount(),
2868 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002869 request.isServiceFromCache(),
2870 request.getSentQueryCount());
Paul Hu18aeccc2022-12-27 08:48:48 +00002871 try {
2872 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2873 } catch (RemoteException e) {
2874 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2875 }
2876 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002877 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002878}