blob: 11683200124d212e3ecee9ff6c3d40c7481d35d6 [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 Huf3fe3332023-10-16 17:13:25 +08001732 .build();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001733 mMdnsSocketClient =
Yuyang Huang7ddf2932023-08-01 18:16:30 +09001734 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider,
Paul Hufd357ef2023-11-01 16:32:45 +08001735 LOGGER.forSubComponent("MdnsMultinetworkSocketClient"), flags);
Paul Hu14667de2023-04-17 22:42:47 +08001736 mMdnsDiscoveryManager = deps.makeMdnsDiscoveryManager(new ExecutorProvider(),
Paul Huf3fe3332023-10-16 17:13:25 +08001737 mMdnsSocketClient, LOGGER.forSubComponent("MdnsDiscoveryManager"), flags);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001738 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1739 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
Yuyang Huangb96a0712023-09-07 15:13:15 +09001740 new AdvertiserCallback(), LOGGER.forSubComponent("MdnsAdvertiser"), flags);
Paul Hu777ed052023-06-19 13:35:15 +00001741 mClock = deps.makeClock();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001742 }
1743
1744 /**
1745 * Dependencies of NsdService, for injection in tests.
1746 */
1747 @VisibleForTesting
1748 public static class Dependencies {
1749 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001750 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001751 *
1752 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001753 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001754 */
1755 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001756 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001757 MDNS_DISCOVERY_MANAGER_VERSION);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001758 }
1759
1760 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001761 * Check whether the MdnsAdvertiser feature is enabled.
1762 *
1763 * @param context The global context information about an app environment.
1764 * @return true if the MdnsAdvertiser feature is enabled.
1765 */
1766 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001767 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001768 MDNS_ADVERTISER_VERSION);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001769 }
1770
1771 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001772 * Get the type allowlist flag value.
1773 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1774 */
1775 @Nullable
1776 public String getTypeAllowlistFlags() {
1777 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1778 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1779 }
1780
1781 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001782 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001783 */
1784 public boolean isFeatureEnabled(Context context, String feature) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001785 return DeviceConfigUtils.isTetheringFeatureEnabled(context, feature);
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001786 }
1787
1788 /**
Yuyang Huangb96a0712023-09-07 15:13:15 +09001789 * @see DeviceConfigUtils#isTetheringFeatureNotChickenedOut
1790 */
Motomu Utsumied4e7ec2023-09-13 14:58:32 +09001791 public boolean isTetheringFeatureNotChickenedOut(Context context, String feature) {
1792 return DeviceConfigUtils.isTetheringFeatureNotChickenedOut(context, feature);
Yuyang Huangb96a0712023-09-07 15:13:15 +09001793 }
1794
1795 /**
Paul Huf3fe3332023-10-16 17:13:25 +08001796 * @see DeviceConfigUtils#isTrunkStableFeatureEnabled
1797 */
1798 public boolean isTrunkStableFeatureEnabled(String feature) {
1799 return DeviceConfigUtils.isTrunkStableFeatureEnabled(feature);
1800 }
1801
1802 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001803 * @see MdnsDiscoveryManager
1804 */
1805 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
Paul Hu14667de2023-04-17 22:42:47 +08001806 @NonNull ExecutorProvider executorProvider,
Paul Huf3fe3332023-10-16 17:13:25 +08001807 @NonNull MdnsMultinetworkSocketClient socketClient, @NonNull SharedLog sharedLog,
1808 @NonNull MdnsFeatureFlags featureFlags) {
1809 return new MdnsDiscoveryManager(
1810 executorProvider, socketClient, sharedLog, featureFlags);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001811 }
1812
1813 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001814 * @see MdnsAdvertiser
1815 */
1816 public MdnsAdvertiser makeMdnsAdvertiser(
1817 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
Yuyang Huangb96a0712023-09-07 15:13:15 +09001818 @NonNull MdnsAdvertiser.AdvertiserCallback cb, @NonNull SharedLog sharedLog,
1819 MdnsFeatureFlags featureFlags) {
1820 return new MdnsAdvertiser(looper, socketProvider, cb, sharedLog, featureFlags);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001821 }
1822
1823 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001824 * @see MdnsSocketProvider
1825 */
Paul Hu14667de2023-04-17 22:42:47 +08001826 public MdnsSocketProvider makeMdnsSocketProvider(@NonNull Context context,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001827 @NonNull Looper looper, @NonNull SharedLog sharedLog,
1828 @NonNull MdnsSocketProvider.SocketRequestMonitor socketCreationCallback) {
1829 return new MdnsSocketProvider(context, looper, sharedLog, socketCreationCallback);
1830 }
1831
1832 /**
1833 * @see DeviceConfig#getInt(String, String, int)
1834 */
1835 public int getDeviceConfigInt(@NonNull String config, int defaultValue) {
1836 return DeviceConfig.getInt(NAMESPACE_TETHERING, config, defaultValue);
1837 }
1838
1839 /**
1840 * @see Binder#getCallingUid()
1841 */
1842 public int getCallingUid() {
1843 return Binder.getCallingUid();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001844 }
Paul Hu777ed052023-06-19 13:35:15 +00001845
1846 /**
1847 * @see NetworkNsdReportedMetrics
1848 */
Paul Hu508a0122023-09-11 15:31:33 +08001849 public NetworkNsdReportedMetrics makeNetworkNsdReportedMetrics(int clientId) {
1850 return new NetworkNsdReportedMetrics(clientId);
Paul Hu777ed052023-06-19 13:35:15 +00001851 }
1852
1853 /**
1854 * @see MdnsUtils.Clock
1855 */
1856 public Clock makeClock() {
1857 return new Clock();
1858 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001859 }
1860
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001861 /**
1862 * Return whether a type is allowlisted to use the Java backend.
1863 * @param type The service type
1864 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1865 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1866 */
1867 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1868 @NonNull String flagPrefix) {
1869 if (type == null) return false;
1870 final String typesConfig = mDeps.getTypeAllowlistFlags();
1871 if (TextUtils.isEmpty(typesConfig)) return false;
1872
1873 final String mappingPrefix = type + ":";
1874 String mappedFlag = null;
1875 for (String mapping : TextUtils.split(typesConfig, ",")) {
1876 if (mapping.startsWith(mappingPrefix)) {
1877 mappedFlag = mapping.substring(mappingPrefix.length());
1878 break;
1879 }
1880 }
1881
1882 if (mappedFlag == null) return false;
1883
1884 return mDeps.isFeatureEnabled(mContext,
1885 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1886 }
1887
1888 private boolean useDiscoveryManagerForType(@Nullable String type) {
1889 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1890 }
1891
1892 private boolean useAdvertiserForType(@Nullable String type) {
1893 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1894 }
1895
paulhu1b35e822022-04-08 14:48:41 +08001896 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001897 HandlerThread thread = new HandlerThread(TAG);
1898 thread.start();
1899 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001900 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001901 return service;
1902 }
1903
paulhu2b9ed952022-02-10 21:58:32 +08001904 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1905 private final StateMachine mStateMachine;
1906
1907 MDnsEventCallback(StateMachine sm) {
1908 mStateMachine = sm;
1909 }
1910
1911 @Override
1912 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1913 mStateMachine.sendMessage(
1914 MDNS_SERVICE_EVENT, status.result, status.id, status);
1915 }
1916
1917 @Override
1918 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1919 mStateMachine.sendMessage(
1920 MDNS_SERVICE_EVENT, status.result, status.id, status);
1921 }
1922
1923 @Override
1924 public void onServiceResolutionStatus(final ResolutionInfo status) {
1925 mStateMachine.sendMessage(
1926 MDNS_SERVICE_EVENT, status.result, status.id, status);
1927 }
1928
1929 @Override
1930 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1931 mStateMachine.sendMessage(
1932 MDNS_SERVICE_EVENT, status.result, status.id, status);
1933 }
1934
1935 @Override
1936 public int getInterfaceVersion() throws RemoteException {
1937 return this.VERSION;
1938 }
1939
1940 @Override
1941 public String getInterfaceHash() throws RemoteException {
1942 return this.HASH;
1943 }
1944 }
1945
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001946 private void sendAllOffloadServiceInfos(@NonNull OffloadEngineInfo offloadEngineInfo) {
1947 final String targetInterface = offloadEngineInfo.mInterfaceName;
1948 final IOffloadEngine offloadEngine = offloadEngineInfo.mOffloadEngine;
1949 final List<MdnsAdvertiser.OffloadServiceInfoWrapper> offloadWrappers =
1950 mAdvertiser.getAllInterfaceOffloadServiceInfos(targetInterface);
1951 for (MdnsAdvertiser.OffloadServiceInfoWrapper wrapper : offloadWrappers) {
1952 try {
1953 offloadEngine.onOffloadServiceUpdated(wrapper.mOffloadServiceInfo);
1954 } catch (RemoteException e) {
1955 // Can happen in regular cases, do not log a stacktrace
1956 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
1957 }
1958 }
1959 }
1960
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001961 private void sendOffloadServiceInfosUpdate(@NonNull String targetInterfaceName,
1962 @NonNull OffloadServiceInfo offloadServiceInfo, boolean isRemove) {
1963 final int count = mOffloadEngines.beginBroadcast();
1964 try {
1965 for (int i = 0; i < count; i++) {
1966 final OffloadEngineInfo offloadEngineInfo =
1967 (OffloadEngineInfo) mOffloadEngines.getBroadcastCookie(i);
1968 final String interfaceName = offloadEngineInfo.mInterfaceName;
1969 if (!targetInterfaceName.equals(interfaceName)
1970 || ((offloadEngineInfo.mOffloadType
1971 & offloadServiceInfo.getOffloadType()) == 0)) {
1972 continue;
1973 }
1974 try {
1975 if (isRemove) {
1976 mOffloadEngines.getBroadcastItem(i).onOffloadServiceRemoved(
1977 offloadServiceInfo);
1978 } else {
1979 mOffloadEngines.getBroadcastItem(i).onOffloadServiceUpdated(
1980 offloadServiceInfo);
1981 }
1982 } catch (RemoteException e) {
1983 // Can happen in regular cases, do not log a stacktrace
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001984 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001985 }
1986 }
1987 } finally {
1988 mOffloadEngines.finishBroadcast();
1989 }
1990 }
1991
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001992 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001993 // TODO: add a callback to notify when a service is being added on each interface (as soon
1994 // as probing starts), and call mOffloadCallbacks. This callback is for
1995 // OFFLOAD_CAPABILITY_FILTER_REPLIES offload type.
1996
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001997 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001998 public void onRegisterServiceSucceeded(int transactionId, NsdServiceInfo registeredInfo) {
1999 mServiceLogs.log("onRegisterServiceSucceeded: transactionId " + transactionId);
2000 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002001 if (clientInfo == null) return;
2002
Paul Hud44e1b72023-06-16 02:07:42 +00002003 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
2004 if (clientRequestId < 0) return;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002005
2006 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
2007 // historical behavior.
2008 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
Paul Hu777ed052023-06-19 13:35:15 +00002009 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu508a0122023-09-11 15:31:33 +08002010 clientInfo.onRegisterServiceSucceeded(clientRequestId, cbInfo, request);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002011 }
2012
2013 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00002014 public void onRegisterServiceFailed(int transactionId, int errorCode) {
2015 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002016 if (clientInfo == null) return;
2017
Paul Hud44e1b72023-06-16 02:07:42 +00002018 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
2019 if (clientRequestId < 0) return;
Paul Hu777ed052023-06-19 13:35:15 +00002020 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu508a0122023-09-11 15:31:33 +08002021 clientInfo.onRegisterServiceFailed(clientRequestId, errorCode, false /* isLegacy */,
2022 transactionId, request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002023 }
2024
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002025 @Override
2026 public void onOffloadStartOrUpdate(@NonNull String interfaceName,
2027 @NonNull OffloadServiceInfo offloadServiceInfo) {
2028 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, false /* isRemove */);
2029 }
2030
2031 @Override
2032 public void onOffloadStop(@NonNull String interfaceName,
2033 @NonNull OffloadServiceInfo offloadServiceInfo) {
2034 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, true /* isRemove */);
2035 }
2036
Paul Hud44e1b72023-06-16 02:07:42 +00002037 private ClientInfo getClientInfoOrLog(int transactionId) {
2038 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002039 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00002040 Log.e(TAG, String.format("Callback for service %d has no client", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002041 }
2042 return clientInfo;
2043 }
2044
Paul Hud44e1b72023-06-16 02:07:42 +00002045 private int getClientRequestIdOrLog(@NonNull ClientInfo info, int transactionId) {
2046 final int clientRequestId = info.getClientRequestId(transactionId);
2047 if (clientRequestId < 0) {
2048 Log.e(TAG, String.format(
2049 "Client request ID not found for service %d", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002050 }
Paul Hud44e1b72023-06-16 02:07:42 +00002051 return clientRequestId;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002052 }
2053 }
2054
Paul Hu2e0a88c2023-03-09 16:05:01 +08002055 private static class ConnectorArgs {
2056 @NonNull public final NsdServiceConnector connector;
2057 @NonNull public final INsdManagerCallback callback;
2058 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002059 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002060
2061 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00002062 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08002063 this.connector = connector;
2064 this.callback = callback;
2065 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002066 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002067 }
2068 }
2069
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002070 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08002071 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09002072 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu101dbf52023-08-09 16:05:20 +08002073 final int uid = mDeps.getCallingUid();
2074 if (cb == null) {
2075 throw new IllegalArgumentException("Unknown client callback from uid=" + uid);
2076 }
Paul Hu2e0a88c2023-03-09 16:05:01 +08002077 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002078 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00002079 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
Paul Hu101dbf52023-08-09 16:05:20 +08002080 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend, uid)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002081 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07002082 }
2083
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002084 private static class ListenerArgs {
2085 public final NsdServiceConnector connector;
2086 public final NsdServiceInfo serviceInfo;
2087 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
2088 this.connector = connector;
2089 this.serviceInfo = serviceInfo;
2090 }
2091 }
2092
Yuyang Huang86d083f2023-12-12 19:56:41 +09002093 private static class AdvertisingArgs {
2094 public final NsdServiceConnector connector;
2095 public final AdvertisingRequest advertisingRequest;
2096
2097 AdvertisingArgs(NsdServiceConnector connector, AdvertisingRequest advertisingRequest) {
2098 this.connector = connector;
2099 this.advertisingRequest = advertisingRequest;
2100 }
2101 }
2102
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002103 private class NsdServiceConnector extends INsdServiceConnector.Stub
2104 implements IBinder.DeathRecipient {
Yuyang Huang86d083f2023-12-12 19:56:41 +09002105
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002106 @Override
Yuyang Huang86d083f2023-12-12 19:56:41 +09002107 public void registerService(int listenerKey, AdvertisingRequest advertisingRequest)
2108 throws RemoteException {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002109 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2110 NsdManager.REGISTER_SERVICE, 0, listenerKey,
Yuyang Huang86d083f2023-12-12 19:56:41 +09002111 new AdvertisingArgs(this, advertisingRequest)
2112 ));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002113 }
2114
2115 @Override
2116 public void unregisterService(int listenerKey) {
2117 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2118 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
Yuyang Huang86d083f2023-12-12 19:56:41 +09002119 new ListenerArgs(this, (NsdServiceInfo) null)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002120 }
2121
2122 @Override
2123 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
2124 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2125 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
2126 new ListenerArgs(this, serviceInfo)));
2127 }
2128
2129 @Override
2130 public void stopDiscovery(int listenerKey) {
Yuyang Huang86d083f2023-12-12 19:56:41 +09002131 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.STOP_DISCOVERY,
2132 0, listenerKey, new ListenerArgs(this, (NsdServiceInfo) null)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002133 }
2134
2135 @Override
2136 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
2137 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2138 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
2139 new ListenerArgs(this, serviceInfo)));
2140 }
2141
2142 @Override
Paul Hub58deb72022-12-26 09:24:42 +00002143 public void stopResolution(int listenerKey) {
Yuyang Huang86d083f2023-12-12 19:56:41 +09002144 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.STOP_RESOLUTION,
2145 0, listenerKey, new ListenerArgs(this, (NsdServiceInfo) null)));
Paul Hub58deb72022-12-26 09:24:42 +00002146 }
2147
2148 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00002149 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
2150 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2151 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
2152 new ListenerArgs(this, serviceInfo)));
2153 }
2154
2155 @Override
2156 public void unregisterServiceInfoCallback(int listenerKey) {
2157 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2158 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
Yuyang Huang86d083f2023-12-12 19:56:41 +09002159 new ListenerArgs(this, (NsdServiceInfo) null)));
Paul Hu18aeccc2022-12-27 08:48:48 +00002160 }
2161
2162 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002163 public void startDaemon() {
Yuyang Huang86d083f2023-12-12 19:56:41 +09002164 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.DAEMON_STARTUP,
2165 new ListenerArgs(this, (NsdServiceInfo) null)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002166 }
2167
2168 @Override
2169 public void binderDied() {
2170 mNsdStateMachine.sendMessage(
2171 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002172
2173 }
2174
2175 @Override
2176 public void registerOffloadEngine(String ifaceName, IOffloadEngine cb,
2177 @OffloadEngine.OffloadCapability long offloadCapabilities,
2178 @OffloadEngine.OffloadType long offloadTypes) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002179 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002180 Objects.requireNonNull(ifaceName);
2181 Objects.requireNonNull(cb);
2182 mNsdStateMachine.sendMessage(
2183 mNsdStateMachine.obtainMessage(NsdManager.REGISTER_OFFLOAD_ENGINE,
2184 new OffloadEngineInfo(cb, ifaceName, offloadCapabilities,
2185 offloadTypes)));
2186 }
2187
2188 @Override
2189 public void unregisterOffloadEngine(IOffloadEngine cb) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002190 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002191 Objects.requireNonNull(cb);
2192 mNsdStateMachine.sendMessage(
2193 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_OFFLOAD_ENGINE, cb));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002194 }
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002195
2196 private static void checkOffloadEnginePermission(Context context) {
2197 if (!SdkLevel.isAtLeastT()) {
2198 throw new SecurityException("API is not available in before API level 33");
2199 }
Yuyang Huangd5896e72023-11-28 13:23:59 +09002200
2201 // REGISTER_NSD_OFFLOAD_ENGINE was only added to the SDK in V.
2202 if (SdkLevel.isAtLeastV() && PermissionUtils.checkAnyPermissionOf(context,
2203 REGISTER_NSD_OFFLOAD_ENGINE)) {
2204 return;
2205 }
2206
2207 // REGISTER_NSD_OFFLOAD_ENGINE cannot be backport to U. In U, check the DEVICE_POWER
2208 // permission instead.
2209 if (!SdkLevel.isAtLeastV() && SdkLevel.isAtLeastU()
2210 && PermissionUtils.checkAnyPermissionOf(context, DEVICE_POWER)) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002211 return;
2212 }
2213 if (PermissionUtils.checkAnyPermissionOf(context, NETWORK_STACK,
2214 PERMISSION_MAINLINE_NETWORK_STACK, NETWORK_SETTINGS)) {
2215 return;
2216 }
2217 throw new SecurityException("Requires one of the following permissions: "
2218 + String.join(", ", List.of(REGISTER_NSD_OFFLOAD_ENGINE, NETWORK_STACK,
2219 PERMISSION_MAINLINE_NETWORK_STACK, NETWORK_SETTINGS)) + ".");
2220 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002221 }
2222
Hugo Benichi912db992017-04-24 16:41:03 +09002223 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07002224 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07002225 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09002226 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
2227 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07002228 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07002229 }
2230
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002231 private int getUniqueId() {
2232 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
2233 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002234 }
2235
Paul Hud44e1b72023-06-16 02:07:42 +00002236 private boolean registerService(int transactionId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09002237 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002238 Log.d(TAG, "registerService: " + transactionId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002239 }
Hugo Benichi6d706442017-04-24 16:19:58 +09002240 String name = service.getServiceName();
2241 String type = service.getServiceType();
2242 int port = service.getPort();
2243 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002244 final int registerInterface = getNetworkInterfaceIndex(service);
2245 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08002246 Log.e(TAG, "Interface to register service on not found");
2247 return false;
2248 }
Paul Hud44e1b72023-06-16 02:07:42 +00002249 return mMDnsManager.registerService(
2250 transactionId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002251 }
2252
Paul Hud44e1b72023-06-16 02:07:42 +00002253 private boolean unregisterService(int transactionId) {
2254 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002255 }
2256
Paul Hud44e1b72023-06-16 02:07:42 +00002257 private boolean discoverServices(int transactionId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08002258 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002259 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
2260 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002261 Log.e(TAG, "Interface to discover service on not found");
2262 return false;
2263 }
Paul Hud44e1b72023-06-16 02:07:42 +00002264 return mMDnsManager.discover(transactionId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002265 }
2266
Paul Hud44e1b72023-06-16 02:07:42 +00002267 private boolean stopServiceDiscovery(int transactionId) {
2268 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002269 }
2270
Paul Hud44e1b72023-06-16 02:07:42 +00002271 private boolean resolveService(int transactionId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002272 final String name = service.getServiceName();
2273 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002274 final int resolveInterface = getNetworkInterfaceIndex(service);
2275 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002276 Log.e(TAG, "Interface to resolve service on not found");
2277 return false;
2278 }
Paul Hud44e1b72023-06-16 02:07:42 +00002279 return mMDnsManager.resolve(transactionId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002280 }
2281
2282 /**
2283 * Guess the interface to use to resolve or discover a service on a specific network.
2284 *
2285 * This is an imperfect guess, as for example the network may be gone or not yet fully
2286 * registered. This is fine as failing is correct if the network is gone, and a client
2287 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
2288 * this is to support the legacy mdnsresponder implementation, which historically resolved
2289 * services on an unspecified network.
2290 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002291 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
2292 final Network network = serviceInfo.getNetwork();
2293 if (network == null) {
2294 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
2295 // provided by NsdService from discovery results, and the service was found on an
2296 // interface that has no app-usable Network).
2297 if (serviceInfo.getInterfaceIndex() != 0) {
2298 return serviceInfo.getInterfaceIndex();
2299 }
2300 return IFACE_IDX_ANY;
2301 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002302
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002303 String interfaceName = getNetworkInterfaceName(network);
2304 if (interfaceName == null) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002305 return IFACE_IDX_ANY;
2306 }
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002307 return getNetworkInterfaceIndexByName(interfaceName);
2308 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002309
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002310 private String getNetworkInterfaceName(@Nullable Network network) {
2311 if (network == null) {
2312 return null;
2313 }
2314 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
2315 if (cm == null) {
2316 Log.wtf(TAG, "No ConnectivityManager");
2317 return null;
2318 }
2319 final LinkProperties lp = cm.getLinkProperties(network);
2320 if (lp == null) {
2321 return null;
2322 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002323 // Only resolve on non-stacked interfaces
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002324 return lp.getInterfaceName();
2325 }
2326
2327 private int getNetworkInterfaceIndexByName(final String ifaceName) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002328 final NetworkInterface iface;
2329 try {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002330 iface = NetworkInterface.getByName(ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002331 } catch (SocketException e) {
2332 Log.e(TAG, "Error querying interface", e);
2333 return IFACE_IDX_ANY;
2334 }
2335
2336 if (iface == null) {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002337 Log.e(TAG, "Interface not found: " + ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002338 return IFACE_IDX_ANY;
2339 }
2340
2341 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002342 }
2343
Paul Hud44e1b72023-06-16 02:07:42 +00002344 private boolean stopResolveService(int transactionId) {
2345 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002346 }
2347
Paul Hud44e1b72023-06-16 02:07:42 +00002348 private boolean getAddrInfo(int transactionId, String hostname, int interfaceIdx) {
2349 return mMDnsManager.getServiceAddress(transactionId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002350 }
2351
Paul Hud44e1b72023-06-16 02:07:42 +00002352 private boolean stopGetAddrInfo(int transactionId) {
2353 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002354 }
2355
2356 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00002357 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2358 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002359
Paul Hub2e67d32023-04-18 05:50:14 +00002360 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2361 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07002362 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00002363
2364 // Dump service and clients logs
2365 pw.println();
Paul Hu14667de2023-04-17 22:42:47 +08002366 pw.println("Logs:");
Paul Hub2e67d32023-04-18 05:50:14 +00002367 pw.increaseIndent();
2368 mServiceLogs.reverseDump(pw);
2369 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002370 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002371
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002372 private abstract static class ClientRequest {
Paul Hud44e1b72023-06-16 02:07:42 +00002373 private final int mTransactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002374 private final long mStartTimeMs;
Paul Hu812e9212023-06-20 06:24:53 +00002375 private int mFoundServiceCount = 0;
2376 private int mLostServiceCount = 0;
2377 private final Set<String> mServices = new ArraySet<>();
Paul Hua6bc4632023-06-26 01:18:29 +00002378 private boolean mIsServiceFromCache = false;
Paul Hubad6fe92023-07-24 21:25:22 +08002379 private int mSentQueryCount = NO_SENT_QUERY_COUNT;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002380
Paul Hu812e9212023-06-20 06:24:53 +00002381 private ClientRequest(int transactionId, long startTimeMs) {
Paul Hud44e1b72023-06-16 02:07:42 +00002382 mTransactionId = transactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002383 mStartTimeMs = startTimeMs;
2384 }
2385
Paul Hu812e9212023-06-20 06:24:53 +00002386 public long calculateRequestDurationMs(long stopTimeMs) {
Paul Hu777ed052023-06-19 13:35:15 +00002387 return stopTimeMs - mStartTimeMs;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002388 }
Paul Hu812e9212023-06-20 06:24:53 +00002389
2390 public void onServiceFound(String serviceName) {
2391 mFoundServiceCount++;
2392 if (mServices.size() <= MAX_SERVICES_COUNT_METRIC_PER_CLIENT) {
2393 mServices.add(serviceName);
2394 }
2395 }
2396
2397 public void onServiceLost() {
2398 mLostServiceCount++;
2399 }
2400
2401 public int getFoundServiceCount() {
2402 return mFoundServiceCount;
2403 }
2404
2405 public int getLostServiceCount() {
2406 return mLostServiceCount;
2407 }
2408
2409 public int getServicesCount() {
2410 return mServices.size();
2411 }
Paul Hua6bc4632023-06-26 01:18:29 +00002412
2413 public void setServiceFromCache(boolean isServiceFromCache) {
2414 mIsServiceFromCache = isServiceFromCache;
2415 }
2416
2417 public boolean isServiceFromCache() {
2418 return mIsServiceFromCache;
2419 }
Paul Hubad6fe92023-07-24 21:25:22 +08002420
2421 public void onQuerySent() {
2422 mSentQueryCount++;
2423 }
2424
2425 public int getSentQueryCount() {
2426 return mSentQueryCount;
2427 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002428 }
2429
2430 private static class LegacyClientRequest extends ClientRequest {
2431 private final int mRequestCode;
2432
Paul Hu812e9212023-06-20 06:24:53 +00002433 private LegacyClientRequest(int transactionId, int requestCode, long startTimeMs) {
2434 super(transactionId, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002435 mRequestCode = requestCode;
2436 }
2437 }
2438
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002439 private abstract static class JavaBackendClientRequest extends ClientRequest {
2440 @Nullable
2441 private final Network mRequestedNetwork;
2442
Paul Hu777ed052023-06-19 13:35:15 +00002443 private JavaBackendClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002444 long startTimeMs) {
2445 super(transactionId, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002446 mRequestedNetwork = requestedNetwork;
2447 }
2448
2449 @Nullable
2450 public Network getRequestedNetwork() {
2451 return mRequestedNetwork;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002452 }
2453 }
2454
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002455 private static class AdvertiserClientRequest extends JavaBackendClientRequest {
Paul Hu777ed052023-06-19 13:35:15 +00002456 private AdvertiserClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002457 long startTimeMs) {
2458 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002459 }
2460 }
2461
2462 private static class DiscoveryManagerRequest extends JavaBackendClientRequest {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002463 @NonNull
2464 private final MdnsListener mListener;
2465
Paul Hud44e1b72023-06-16 02:07:42 +00002466 private DiscoveryManagerRequest(int transactionId, @NonNull MdnsListener listener,
Paul Hu812e9212023-06-20 06:24:53 +00002467 @Nullable Network requestedNetwork, long startTimeMs) {
2468 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002469 mListener = listener;
2470 }
2471 }
2472
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002473 /* Information tracked per client */
2474 private class ClientInfo {
2475
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002476 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002477 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002478 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002479 private NsdServiceInfo mResolvedService;
2480
Paul Hud44e1b72023-06-16 02:07:42 +00002481 /* A map from client request ID (listenerKey) to the request */
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002482 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08002483
Luke Huangf7277ed2021-07-12 21:15:10 +08002484 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002485 private boolean mIsPreSClient = false;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002486 private final int mUid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002487 // The flag of using java backend if the client's target SDK >= U
2488 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002489 // Store client logs
2490 private final SharedLog mClientLogs;
Paul Hucdef3532023-06-18 14:47:35 +00002491 // Report the nsd metrics data
2492 private final NetworkNsdReportedMetrics mMetrics;
Luke Huangf7277ed2021-07-12 21:15:10 +08002493
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002494 private ClientInfo(INsdManagerCallback cb, int uid, boolean useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +00002495 SharedLog sharedLog, NetworkNsdReportedMetrics metrics) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002496 mCb = cb;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002497 mUid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002498 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002499 mClientLogs = sharedLog;
2500 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Paul Hucdef3532023-06-18 14:47:35 +00002501 mMetrics = metrics;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002502 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002503
2504 @Override
2505 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06002506 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07002507 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002508 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002509 sb.append("mUseJavaBackend ").append(mUseJavaBackend).append("\n");
2510 sb.append("mUid ").append(mUid).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002511 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002512 int clientRequestId = mClientRequests.keyAt(i);
2513 sb.append("clientRequestId ")
2514 .append(clientRequestId)
2515 .append(" transactionId ").append(mClientRequests.valueAt(i).mTransactionId)
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002516 .append(" type ").append(
2517 mClientRequests.valueAt(i).getClass().getSimpleName())
2518 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07002519 }
2520 return sb.toString();
2521 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002522
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002523 private boolean isPreSClient() {
2524 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08002525 }
2526
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002527 private void setPreSClient() {
2528 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08002529 }
2530
Paul Hu812e9212023-06-20 06:24:53 +00002531 private MdnsListener unregisterMdnsListenerFromRequest(ClientRequest request) {
Paul Hue4f5f252023-02-16 21:13:47 +08002532 final MdnsListener listener =
2533 ((DiscoveryManagerRequest) request).mListener;
2534 mMdnsDiscoveryManager.unregisterListener(
2535 listener.getListenedServiceType(), listener);
Paul Hu812e9212023-06-20 06:24:53 +00002536 return listener;
Paul Hue4f5f252023-02-16 21:13:47 +08002537 }
2538
Dave Plattfeff2af2014-03-07 14:48:22 -08002539 // Remove any pending requests from the global map when we get rid of a client,
2540 // and send cancellations to the daemon.
2541 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00002542 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09002543 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002544 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002545 final int clientRequestId = mClientRequests.keyAt(i);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002546 final ClientRequest request = mClientRequests.valueAt(i);
Paul Hud44e1b72023-06-16 02:07:42 +00002547 final int transactionId = request.mTransactionId;
2548 mTransactionIdToClientInfoMap.remove(transactionId);
paulhub2225702021-11-17 09:35:33 +08002549 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002550 Log.d(TAG, "Terminating clientRequestId " + clientRequestId
2551 + " transactionId " + transactionId
2552 + " type " + mClientRequests.get(clientRequestId));
paulhub2225702021-11-17 09:35:33 +08002553 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002554
2555 if (request instanceof DiscoveryManagerRequest) {
Paul Hu812e9212023-06-20 06:24:53 +00002556 final MdnsListener listener = unregisterMdnsListenerFromRequest(request);
2557 if (listener instanceof DiscoveryListener) {
Paul Hu508a0122023-09-11 15:31:33 +08002558 mMetrics.reportServiceDiscoveryStop(false /* isLegacy */, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00002559 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2560 request.getFoundServiceCount(),
2561 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002562 request.getServicesCount(),
2563 request.getSentQueryCount());
Paul Hu60149052023-07-31 14:26:08 +08002564 } else if (listener instanceof ResolutionListener) {
Paul Hu508a0122023-09-11 15:31:33 +08002565 mMetrics.reportServiceResolutionStop(false /* isLegacy */, transactionId,
Paul Hu60149052023-07-31 14:26:08 +08002566 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Huddce5912023-08-01 10:26:49 +08002567 } else if (listener instanceof ServiceInfoListener) {
2568 mMetrics.reportServiceInfoCallbackUnregistered(transactionId,
2569 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2570 request.getFoundServiceCount(),
2571 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002572 request.isServiceFromCache(),
2573 request.getSentQueryCount());
Paul Hu812e9212023-06-20 06:24:53 +00002574 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002575 continue;
2576 }
2577
2578 if (request instanceof AdvertiserClientRequest) {
Paul Hu043bcd42023-07-14 16:38:25 +08002579 final AdvertiserMetrics metrics =
2580 mAdvertiser.getAdvertiserMetrics(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00002581 mAdvertiser.removeService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002582 mMetrics.reportServiceUnregistration(false /* isLegacy */, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002583 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2584 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2585 metrics.mConflictDuringProbingCount,
2586 metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002587 continue;
2588 }
2589
2590 if (!(request instanceof LegacyClientRequest)) {
2591 throw new IllegalStateException("Unknown request type: " + request.getClass());
2592 }
2593
2594 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08002595 case NsdManager.DISCOVER_SERVICES:
Paul Hud44e1b72023-06-16 02:07:42 +00002596 stopServiceDiscovery(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002597 mMetrics.reportServiceDiscoveryStop(true /* isLegacy */, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00002598 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2599 request.getFoundServiceCount(),
2600 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002601 request.getServicesCount(),
2602 NO_SENT_QUERY_COUNT);
Dave Plattfeff2af2014-03-07 14:48:22 -08002603 break;
2604 case NsdManager.RESOLVE_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002605 stopResolveService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002606 mMetrics.reportServiceResolutionStop(true /* isLegacy */, transactionId,
Paul Hu60149052023-07-31 14:26:08 +08002607 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Dave Plattfeff2af2014-03-07 14:48:22 -08002608 break;
2609 case NsdManager.REGISTER_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002610 unregisterService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002611 mMetrics.reportServiceUnregistration(true /* isLegacy */, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002612 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2613 NO_PACKET /* repliedRequestsCount */,
2614 NO_PACKET /* sentPacketCount */,
2615 0 /* conflictDuringProbingCount */,
2616 0 /* conflictAfterProbingCount */);
Dave Plattfeff2af2014-03-07 14:48:22 -08002617 break;
2618 default:
2619 break;
2620 }
2621 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002622 mClientRequests.clear();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002623 updateMulticastLock();
2624 }
2625
2626 /**
2627 * Returns true if this client has any Java backend request that requests one of the given
2628 * networks.
2629 */
2630 boolean hasAnyJavaBackendRequestForNetworks(@NonNull ArraySet<Network> networks) {
2631 for (int i = 0; i < mClientRequests.size(); i++) {
2632 final ClientRequest req = mClientRequests.valueAt(i);
2633 if (!(req instanceof JavaBackendClientRequest)) {
2634 continue;
2635 }
2636 final Network reqNetwork = ((JavaBackendClientRequest) mClientRequests.valueAt(i))
2637 .getRequestedNetwork();
2638 if (MdnsUtils.isAnyNetworkMatched(reqNetwork, networks)) {
2639 return true;
2640 }
2641 }
2642 return false;
Dave Plattfeff2af2014-03-07 14:48:22 -08002643 }
2644
Paul Hud44e1b72023-06-16 02:07:42 +00002645 // mClientRequests is a sparse array of client request id -> ClientRequest. For a given
2646 // transaction id, return the corresponding client request id.
2647 private int getClientRequestId(final int transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002648 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002649 if (mClientRequests.valueAt(i).mTransactionId == transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002650 return mClientRequests.keyAt(i);
2651 }
Christopher Lane74411222014-04-25 18:39:07 -07002652 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002653 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07002654 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002655
Paul Hub2e67d32023-04-18 05:50:14 +00002656 private void log(String message) {
2657 mClientLogs.log(message);
2658 }
2659
Paul Hu508a0122023-09-11 15:31:33 +08002660 private static boolean isLegacyClientRequest(@NonNull ClientRequest request) {
2661 return !(request instanceof DiscoveryManagerRequest)
2662 && !(request instanceof AdvertiserClientRequest);
2663 }
2664
2665 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info,
2666 ClientRequest request) {
2667 mMetrics.reportServiceDiscoveryStarted(
2668 isLegacyClientRequest(request), request.mTransactionId);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002669 try {
2670 mCb.onDiscoverServicesStarted(listenerKey, info);
2671 } catch (RemoteException e) {
2672 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
2673 }
2674 }
Paul Hu508a0122023-09-11 15:31:33 +08002675 void onDiscoverServicesFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2676 onDiscoverServicesFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2677 0L /* durationMs */);
Paul Hu812e9212023-06-20 06:24:53 +00002678 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002679
Paul Hu508a0122023-09-11 15:31:33 +08002680 void onDiscoverServicesFailed(int listenerKey, int error, boolean isLegacy,
2681 int transactionId, long durationMs) {
2682 mMetrics.reportServiceDiscoveryFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002683 try {
2684 mCb.onDiscoverServicesFailed(listenerKey, error);
2685 } catch (RemoteException e) {
2686 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
2687 }
2688 }
2689
Paul Hu812e9212023-06-20 06:24:53 +00002690 void onServiceFound(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2691 request.onServiceFound(info.getServiceName());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002692 try {
2693 mCb.onServiceFound(listenerKey, info);
2694 } catch (RemoteException e) {
2695 Log.e(TAG, "Error calling onServiceFound(", e);
2696 }
2697 }
2698
Paul Hu812e9212023-06-20 06:24:53 +00002699 void onServiceLost(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2700 request.onServiceLost();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002701 try {
2702 mCb.onServiceLost(listenerKey, info);
2703 } catch (RemoteException e) {
2704 Log.e(TAG, "Error calling onServiceLost(", e);
2705 }
2706 }
2707
2708 void onStopDiscoveryFailed(int listenerKey, int error) {
2709 try {
2710 mCb.onStopDiscoveryFailed(listenerKey, error);
2711 } catch (RemoteException e) {
2712 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
2713 }
2714 }
2715
Paul Hu812e9212023-06-20 06:24:53 +00002716 void onStopDiscoverySucceeded(int listenerKey, ClientRequest request) {
2717 mMetrics.reportServiceDiscoveryStop(
Paul Hu508a0122023-09-11 15:31:33 +08002718 isLegacyClientRequest(request),
Paul Hu812e9212023-06-20 06:24:53 +00002719 request.mTransactionId,
2720 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2721 request.getFoundServiceCount(),
2722 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002723 request.getServicesCount(),
2724 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002725 try {
2726 mCb.onStopDiscoverySucceeded(listenerKey);
2727 } catch (RemoteException e) {
2728 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2729 }
2730 }
2731
Paul Hu508a0122023-09-11 15:31:33 +08002732 void onRegisterServiceFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2733 onRegisterServiceFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2734 0L /* durationMs */);
Paul Hu777ed052023-06-19 13:35:15 +00002735 }
2736
Paul Hu508a0122023-09-11 15:31:33 +08002737 void onRegisterServiceFailed(int listenerKey, int error, boolean isLegacy,
2738 int transactionId, long durationMs) {
2739 mMetrics.reportServiceRegistrationFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002740 try {
2741 mCb.onRegisterServiceFailed(listenerKey, error);
2742 } catch (RemoteException e) {
2743 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2744 }
2745 }
2746
Paul Hu508a0122023-09-11 15:31:33 +08002747 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info,
2748 ClientRequest request) {
2749 mMetrics.reportServiceRegistrationSucceeded(isLegacyClientRequest(request),
2750 request.mTransactionId,
2751 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002752 try {
2753 mCb.onRegisterServiceSucceeded(listenerKey, info);
2754 } catch (RemoteException e) {
2755 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2756 }
2757 }
2758
2759 void onUnregisterServiceFailed(int listenerKey, int error) {
2760 try {
2761 mCb.onUnregisterServiceFailed(listenerKey, error);
2762 } catch (RemoteException e) {
2763 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2764 }
2765 }
2766
Paul Hu508a0122023-09-11 15:31:33 +08002767 void onUnregisterServiceSucceeded(int listenerKey, ClientRequest request,
Paul Hu043bcd42023-07-14 16:38:25 +08002768 AdvertiserMetrics metrics) {
Paul Hu508a0122023-09-11 15:31:33 +08002769 mMetrics.reportServiceUnregistration(isLegacyClientRequest(request),
2770 request.mTransactionId,
2771 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hu043bcd42023-07-14 16:38:25 +08002772 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2773 metrics.mConflictDuringProbingCount, metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002774 try {
2775 mCb.onUnregisterServiceSucceeded(listenerKey);
2776 } catch (RemoteException e) {
2777 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2778 }
2779 }
2780
Paul Hu508a0122023-09-11 15:31:33 +08002781 void onResolveServiceFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2782 onResolveServiceFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2783 0L /* durationMs */);
Paul Hua6bc4632023-06-26 01:18:29 +00002784 }
2785
Paul Hu508a0122023-09-11 15:31:33 +08002786 void onResolveServiceFailed(int listenerKey, int error, boolean isLegacy,
2787 int transactionId, long durationMs) {
2788 mMetrics.reportServiceResolutionFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002789 try {
2790 mCb.onResolveServiceFailed(listenerKey, error);
2791 } catch (RemoteException e) {
2792 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2793 }
2794 }
2795
Paul Hua6bc4632023-06-26 01:18:29 +00002796 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info,
2797 ClientRequest request) {
2798 mMetrics.reportServiceResolved(
Paul Hu508a0122023-09-11 15:31:33 +08002799 isLegacyClientRequest(request),
Paul Hua6bc4632023-06-26 01:18:29 +00002800 request.mTransactionId,
2801 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hubad6fe92023-07-24 21:25:22 +08002802 request.isServiceFromCache(),
2803 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002804 try {
2805 mCb.onResolveServiceSucceeded(listenerKey, info);
2806 } catch (RemoteException e) {
2807 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2808 }
2809 }
Paul Hub58deb72022-12-26 09:24:42 +00002810
2811 void onStopResolutionFailed(int listenerKey, int error) {
2812 try {
2813 mCb.onStopResolutionFailed(listenerKey, error);
2814 } catch (RemoteException e) {
2815 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2816 }
2817 }
2818
Paul Hu60149052023-07-31 14:26:08 +08002819 void onStopResolutionSucceeded(int listenerKey, ClientRequest request) {
2820 mMetrics.reportServiceResolutionStop(
Paul Hu508a0122023-09-11 15:31:33 +08002821 isLegacyClientRequest(request),
Paul Hu60149052023-07-31 14:26:08 +08002822 request.mTransactionId,
2823 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hub58deb72022-12-26 09:24:42 +00002824 try {
2825 mCb.onStopResolutionSucceeded(listenerKey);
2826 } catch (RemoteException e) {
2827 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2828 }
2829 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002830
2831 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
Paul Huddce5912023-08-01 10:26:49 +08002832 mMetrics.reportServiceInfoCallbackRegistrationFailed(NO_TRANSACTION);
Paul Hu18aeccc2022-12-27 08:48:48 +00002833 try {
2834 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2835 } catch (RemoteException e) {
2836 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2837 }
2838 }
2839
Paul Huddce5912023-08-01 10:26:49 +08002840 void onServiceInfoCallbackRegistered(int transactionId) {
2841 mMetrics.reportServiceInfoCallbackRegistered(transactionId);
2842 }
2843
2844 void onServiceUpdated(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2845 request.onServiceFound(info.getServiceName());
Paul Hu18aeccc2022-12-27 08:48:48 +00002846 try {
2847 mCb.onServiceUpdated(listenerKey, info);
2848 } catch (RemoteException e) {
2849 Log.e(TAG, "Error calling onServiceUpdated", e);
2850 }
2851 }
2852
Paul Huddce5912023-08-01 10:26:49 +08002853 void onServiceUpdatedLost(int listenerKey, ClientRequest request) {
2854 request.onServiceLost();
Paul Hu18aeccc2022-12-27 08:48:48 +00002855 try {
2856 mCb.onServiceUpdatedLost(listenerKey);
2857 } catch (RemoteException e) {
2858 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2859 }
2860 }
2861
Paul Huddce5912023-08-01 10:26:49 +08002862 void onServiceInfoCallbackUnregistered(int listenerKey, ClientRequest request) {
2863 mMetrics.reportServiceInfoCallbackUnregistered(
2864 request.mTransactionId,
2865 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2866 request.getFoundServiceCount(),
2867 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002868 request.isServiceFromCache(),
2869 request.getSentQueryCount());
Paul Hu18aeccc2022-12-27 08:48:48 +00002870 try {
2871 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2872 } catch (RemoteException e) {
2873 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2874 }
2875 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002876 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002877}