blob: 0feda6e1009f457483b4d34cd2f1b159c781a648 [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;
Kangping Dong1f1a3792023-12-10 22:05:04 +080057import android.net.nsd.DiscoveryRequest;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070058import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090059import android.net.nsd.INsdManagerCallback;
60import android.net.nsd.INsdServiceConnector;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090061import android.net.nsd.IOffloadEngine;
paulhu2b9ed952022-02-10 21:58:32 +080062import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070063import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080064import android.net.nsd.NsdServiceInfo;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090065import android.net.nsd.OffloadEngine;
66import android.net.nsd.OffloadServiceInfo;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090067import android.net.wifi.WifiManager;
Paul Hub2e67d32023-04-18 05:50:14 +000068import android.os.Binder;
Yuyang Huangfc831702023-08-21 17:48:48 +090069import android.os.Build;
Hugo Benichi803a2f02017-04-24 11:35:06 +090070import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080071import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090072import android.os.IBinder;
Paul Hu4bd98ef2023-01-12 13:42:07 +080073import android.os.Looper;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070074import android.os.Message;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090075import android.os.RemoteCallbackList;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090076import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070077import android.os.UserHandle;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090078import android.provider.DeviceConfig;
Paul Hu23fa2022023-01-13 22:57:24 +080079import android.text.TextUtils;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090080import android.util.ArraySet;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090081import android.util.Log;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +090082import android.util.Pair;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070083import android.util.SparseArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070084
paulhua262cc12019-08-12 16:25:11 +080085import com.android.internal.annotations.VisibleForTesting;
Paul Hub2e67d32023-04-18 05:50:14 +000086import com.android.internal.util.IndentingPrintWriter;
paulhua262cc12019-08-12 16:25:11 +080087import com.android.internal.util.State;
88import com.android.internal.util.StateMachine;
Paul Hucdef3532023-06-18 14:47:35 +000089import com.android.metrics.NetworkNsdReportedMetrics;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090090import com.android.modules.utils.build.SdkLevel;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090091import com.android.net.module.util.CollectionUtils;
Paul Hu4bd98ef2023-01-12 13:42:07 +080092import com.android.net.module.util.DeviceConfigUtils;
Yuyang Huanga6a6ff92023-04-24 13:33:34 +090093import com.android.net.module.util.InetAddressUtils;
paulhu3ffffe72021-09-16 10:15:22 +080094import com.android.net.module.util.PermissionUtils;
Paul Hub2e67d32023-04-18 05:50:14 +000095import com.android.net.module.util.SharedLog;
Paul Hu4bd98ef2023-01-12 13:42:07 +080096import com.android.server.connectivity.mdns.ExecutorProvider;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090097import com.android.server.connectivity.mdns.MdnsAdvertiser;
Yuyang Huange5cba9c2023-11-02 18:05:47 +090098import com.android.server.connectivity.mdns.MdnsAdvertisingOptions;
Paul Hu4bd98ef2023-01-12 13:42:07 +080099import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
Yuyang Huangb96a0712023-09-07 15:13:15 +0900100import com.android.server.connectivity.mdns.MdnsFeatureFlags;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900101import com.android.server.connectivity.mdns.MdnsInterfaceSocket;
Paul Hu4bd98ef2023-01-12 13:42:07 +0800102import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
Paul Hu23fa2022023-01-13 22:57:24 +0800103import com.android.server.connectivity.mdns.MdnsSearchOptions;
104import com.android.server.connectivity.mdns.MdnsServiceBrowserListener;
105import com.android.server.connectivity.mdns.MdnsServiceInfo;
Paul Hu4bd98ef2023-01-12 13:42:07 +0800106import com.android.server.connectivity.mdns.MdnsSocketProvider;
Yuyang Huangde802c82023-05-02 17:14:22 +0900107import com.android.server.connectivity.mdns.util.MdnsUtils;
paulhua262cc12019-08-12 16:25:11 +0800108
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700109import java.io.FileDescriptor;
110import java.io.PrintWriter;
Yuyang Huangaa0e9602023-03-17 12:43:09 +0900111import java.net.Inet6Address;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700112import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900113import java.net.NetworkInterface;
114import java.net.SocketException;
115import java.net.UnknownHostException;
Paul Hu2b865912023-03-06 14:27:53 +0800116import java.util.ArrayList;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900117import java.util.Arrays;
Kangping Dong5af24b62023-12-10 21:41:16 +0800118import java.util.Collection;
Yuyang Huang170d42f2023-12-09 15:26:16 +0900119import java.util.Collections;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700120import java.util.HashMap;
Kangping Dong5af24b62023-12-10 21:41:16 +0800121import java.util.LinkedHashMap;
Paul Hu23fa2022023-01-13 22:57:24 +0800122import java.util.List;
Paul Hu75069ed2023-01-14 00:31:09 +0800123import java.util.Map;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900124import java.util.Objects;
Paul Hu812e9212023-06-20 06:24:53 +0000125import java.util.Set;
Paul Hu23fa2022023-01-13 22:57:24 +0800126import java.util.regex.Matcher;
127import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700128
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700129/**
130 * Network Service Discovery Service handles remote service discovery operation requests by
131 * implementing the INsdManager interface.
132 *
133 * @hide
134 */
Yuyang Huangfc831702023-08-21 17:48:48 +0900135@RequiresApi(Build.VERSION_CODES.TIRAMISU)
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700136public class NsdService extends INsdManager.Stub {
137 private static final String TAG = "NsdService";
138 private static final String MDNS_TAG = "mDnsConnector";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900139 /**
140 * Enable discovery using the Java DiscoveryManager, instead of the legacy mdnsresponder
141 * implementation.
142 */
Paul Hu4bd98ef2023-01-12 13:42:07 +0800143 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +0800144 private static final String LOCAL_DOMAIN_NAME = "local";
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700145
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900146 /**
147 * Enable advertising using the Java MdnsAdvertiser, instead of the legacy mdnsresponder
148 * implementation.
149 */
150 private static final String MDNS_ADVERTISER_VERSION = "mdns_advertiser_version";
151
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900152 /**
153 * Comma-separated list of type:flag mappings indicating the flags to use to allowlist
154 * discovery/advertising using MdnsDiscoveryManager / MdnsAdvertiser for a given type.
155 *
156 * For example _mytype._tcp.local and _othertype._tcp.local would be configured with:
157 * _mytype._tcp:mytype,_othertype._tcp.local:othertype
158 *
159 * In which case the flags:
160 * "mdns_discovery_manager_allowlist_mytype_version",
161 * "mdns_advertiser_allowlist_mytype_version",
162 * "mdns_discovery_manager_allowlist_othertype_version",
163 * "mdns_advertiser_allowlist_othertype_version"
164 * would be used to toggle MdnsDiscoveryManager / MdnsAdvertiser for each type. The flags will
165 * be read with
Motomu Utsumi624aeb42023-08-15 15:52:27 +0900166 * {@link DeviceConfigUtils#isTetheringFeatureEnabled}
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900167 *
168 * @see #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX
169 * @see #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX
170 * @see #MDNS_ALLOWLIST_FLAG_SUFFIX
171 */
172 private static final String MDNS_TYPE_ALLOWLIST_FLAGS = "mdns_type_allowlist_flags";
173
174 private static final String MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX =
175 "mdns_discovery_manager_allowlist_";
176 private static final String MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX =
177 "mdns_advertiser_allowlist_";
178 private static final String MDNS_ALLOWLIST_FLAG_SUFFIX = "_version";
179
Remi NGUYEN VAN0ca094b2023-09-13 16:27:12 +0900180 private static final String FORCE_ENABLE_FLAG_FOR_TEST_PREFIX = "test_";
Kangping Dong5af24b62023-12-10 21:41:16 +0800181
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900182 @VisibleForTesting
183 static final String MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
184 "mdns_config_running_app_active_importance_cutoff";
185 @VisibleForTesting
186 static final int DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
187 ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
188 private final int mRunningAppActiveImportanceCutoff;
189
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900190 public static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +0000191 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900192 private static final int IFACE_IDX_ANY = 0;
Paul Hu812e9212023-06-20 06:24:53 +0000193 private static final int MAX_SERVICES_COUNT_METRIC_PER_CLIENT = 100;
194 @VisibleForTesting
195 static final int NO_TRANSACTION = -1;
Paul Hubad6fe92023-07-24 21:25:22 +0800196 private static final int NO_SENT_QUERY_COUNT = 0;
197 private static final int DISCOVERY_QUERY_SENT_CALLBACK = 1000;
Kangping Dong5af24b62023-12-10 21:41:16 +0800198 private static final int MAX_SUBTYPE_COUNT = 100;
Paul Hu14667de2023-04-17 22:42:47 +0800199 private static final SharedLog LOGGER = new SharedLog("serviceDiscovery");
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700200
Hugo Benichi32be63d2017-04-05 14:06:11 +0900201 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900202 private final NsdStateMachine mNsdStateMachine;
Ken Chen80c9f6f2023-11-15 18:24:54 +0800203 // It can be null on V+ device since mdns native service provided by netd is removed.
204 private final @Nullable MDnsManager mMDnsManager;
paulhu2b9ed952022-02-10 21:58:32 +0800205 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900206 @NonNull
207 private final Dependencies mDeps;
208 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800209 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900210 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800211 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900212 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800213 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900214 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900215 private final MdnsAdvertiser mAdvertiser;
Paul Hu777ed052023-06-19 13:35:15 +0000216 @NonNull
217 private final Clock mClock;
Paul Hu14667de2023-04-17 22:42:47 +0800218 private final SharedLog mServiceLogs = LOGGER.forSubComponent(TAG);
Paul Hu23fa2022023-01-13 22:57:24 +0800219 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800220 // state machine thread. If change this outside state machine, it will need to introduce
221 // synchronization.
222 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800223 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700224
225 /**
226 * Clients receiving asynchronous messages
227 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900228 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700229
Paul Hud44e1b72023-06-16 02:07:42 +0000230 /* A map from transaction(unique) id to client info */
231 private final SparseArray<ClientInfo> mTransactionIdToClientInfoMap = new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700232
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900233 // Note this is not final to avoid depending on the Wi-Fi service starting before NsdService
234 @Nullable
235 private WifiManager.MulticastLock mHeldMulticastLock;
236 // Fulfilled network requests that require the Wi-Fi lock: key is the obtained Network
237 // (non-null), value is the requested Network (nullable)
238 @NonNull
239 private final ArraySet<Network> mWifiLockRequiredNetworks = new ArraySet<>();
240 @NonNull
241 private final ArraySet<Integer> mRunningAppActiveUids = new ArraySet<>();
242
Luke Huang05298582021-06-13 16:52:05 +0000243 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700244
Hugo Benichi32be63d2017-04-05 14:06:11 +0900245 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700246 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800247 // The count of the connected legacy clients.
248 private int mLegacyClientCount = 0;
Paul Hub2e67d32023-04-18 05:50:14 +0000249 // The number of client that ever connected.
250 private int mClientNumberId = 1;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700251
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900252 private final RemoteCallbackList<IOffloadEngine> mOffloadEngines =
253 new RemoteCallbackList<>();
254
255 private static class OffloadEngineInfo {
256 @NonNull final String mInterfaceName;
257 final long mOffloadCapabilities;
258 final long mOffloadType;
259 @NonNull final IOffloadEngine mOffloadEngine;
260
261 OffloadEngineInfo(@NonNull IOffloadEngine offloadEngine,
262 @NonNull String interfaceName, long capabilities, long offloadType) {
263 this.mOffloadEngine = offloadEngine;
264 this.mInterfaceName = interfaceName;
265 this.mOffloadCapabilities = capabilities;
266 this.mOffloadType = offloadType;
267 }
268 }
269
Paul Hu812e9212023-06-20 06:24:53 +0000270 @VisibleForTesting
271 static class MdnsListener implements MdnsServiceBrowserListener {
Paul Hud44e1b72023-06-16 02:07:42 +0000272 protected final int mClientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800273 protected final int mTransactionId;
274 @NonNull
Paul Hu23fa2022023-01-13 22:57:24 +0800275 protected final String mListenedServiceType;
276
Kangping Dong97b2adc2024-01-11 16:00:37 +0800277 MdnsListener(int clientRequestId, int transactionId, @NonNull String listenedServiceType) {
Paul Hud44e1b72023-06-16 02:07:42 +0000278 mClientRequestId = clientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800279 mTransactionId = transactionId;
Paul Hu23fa2022023-01-13 22:57:24 +0800280 mListenedServiceType = listenedServiceType;
281 }
282
283 @NonNull
284 public String getListenedServiceType() {
285 return mListenedServiceType;
286 }
287
288 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000289 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
290 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800291
292 @Override
293 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
294
295 @Override
296 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
297
298 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000299 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
300 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800301
302 @Override
303 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
304
305 @Override
306 public void onSearchStoppedWithError(int error) { }
307
308 @Override
309 public void onSearchFailedToStart() { }
310
311 @Override
Paul Hubad6fe92023-07-24 21:25:22 +0800312 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
313 int sentQueryTransactionId) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800314
315 @Override
316 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
317 }
318
319 private class DiscoveryListener extends MdnsListener {
320
Paul Hud44e1b72023-06-16 02:07:42 +0000321 DiscoveryListener(int clientRequestId, int transactionId,
Kangping Dong97b2adc2024-01-11 16:00:37 +0800322 @NonNull String listenServiceType) {
323 super(clientRequestId, transactionId, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800324 }
325
326 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000327 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
328 boolean isServiceFromCache) {
Paul Hu019621e2023-01-13 23:26:49 +0800329 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
330 NsdManager.SERVICE_FOUND,
Paul Hua6bc4632023-06-26 01:18:29 +0000331 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu23fa2022023-01-13 22:57:24 +0800332 }
333
334 @Override
335 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800336 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
337 NsdManager.SERVICE_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000338 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800339 }
Paul Hubad6fe92023-07-24 21:25:22 +0800340
341 @Override
342 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
343 int sentQueryTransactionId) {
344 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
345 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
346 }
Paul Hu23fa2022023-01-13 22:57:24 +0800347 }
348
Paul Hu75069ed2023-01-14 00:31:09 +0800349 private class ResolutionListener extends MdnsListener {
350
Paul Hud44e1b72023-06-16 02:07:42 +0000351 ResolutionListener(int clientRequestId, int transactionId,
Kangping Dong97b2adc2024-01-11 16:00:37 +0800352 @NonNull String listenServiceType) {
353 super(clientRequestId, transactionId, listenServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800354 }
355
356 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000357 public void onServiceFound(MdnsServiceInfo serviceInfo, boolean isServiceFromCache) {
Paul Hu75069ed2023-01-14 00:31:09 +0800358 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
359 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
Paul Hua6bc4632023-06-26 01:18:29 +0000360 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu75069ed2023-01-14 00:31:09 +0800361 }
Paul Hubad6fe92023-07-24 21:25:22 +0800362
363 @Override
364 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
365 int sentQueryTransactionId) {
366 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
367 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
368 }
Paul Hu75069ed2023-01-14 00:31:09 +0800369 }
370
Paul Hu30bd70d2023-02-07 13:20:56 +0000371 private class ServiceInfoListener extends MdnsListener {
372
Paul Hud44e1b72023-06-16 02:07:42 +0000373 ServiceInfoListener(int clientRequestId, int transactionId,
Kangping Dong97b2adc2024-01-11 16:00:37 +0800374 @NonNull String listenServiceType) {
375 super(clientRequestId, transactionId, listenServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +0000376 }
377
378 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000379 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
380 boolean isServiceFromCache) {
Paul Hu30bd70d2023-02-07 13:20:56 +0000381 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
382 NsdManager.SERVICE_UPDATED,
Paul Hua6bc4632023-06-26 01:18:29 +0000383 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu30bd70d2023-02-07 13:20:56 +0000384 }
385
386 @Override
387 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) {
388 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
389 NsdManager.SERVICE_UPDATED,
Paul Hud44e1b72023-06-16 02:07:42 +0000390 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000391 }
392
393 @Override
394 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) {
395 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
396 NsdManager.SERVICE_UPDATED_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000397 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000398 }
Paul Hubad6fe92023-07-24 21:25:22 +0800399
400 @Override
401 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
402 int sentQueryTransactionId) {
403 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
404 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
405 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000406 }
407
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900408 private class SocketRequestMonitor implements MdnsSocketProvider.SocketRequestMonitor {
409 @Override
410 public void onSocketRequestFulfilled(@Nullable Network socketNetwork,
411 @NonNull MdnsInterfaceSocket socket, @NonNull int[] transports) {
412 // The network may be null for Wi-Fi SoftAp interfaces (tethering), but there is no APF
413 // filtering on such interfaces, so taking the multicast lock is not necessary to
414 // disable APF filtering of multicast.
415 if (socketNetwork == null
416 || !CollectionUtils.contains(transports, TRANSPORT_WIFI)
417 || CollectionUtils.contains(transports, TRANSPORT_VPN)) {
418 return;
419 }
420
421 if (mWifiLockRequiredNetworks.add(socketNetwork)) {
422 updateMulticastLock();
423 }
424 }
425
426 @Override
427 public void onSocketDestroyed(@Nullable Network socketNetwork,
428 @NonNull MdnsInterfaceSocket socket) {
429 if (mWifiLockRequiredNetworks.remove(socketNetwork)) {
430 updateMulticastLock();
431 }
432 }
433 }
434
435 private class UidImportanceListener implements ActivityManager.OnUidImportanceListener {
436 private final Handler mHandler;
437
438 private UidImportanceListener(Handler handler) {
439 mHandler = handler;
440 }
441
442 @Override
443 public void onUidImportance(int uid, int importance) {
444 mHandler.post(() -> handleUidImportanceChanged(uid, importance));
445 }
446 }
447
448 private void handleUidImportanceChanged(int uid, int importance) {
449 // Lower importance values are more "important"
450 final boolean modified = importance <= mRunningAppActiveImportanceCutoff
451 ? mRunningAppActiveUids.add(uid)
452 : mRunningAppActiveUids.remove(uid);
453 if (modified) {
454 updateMulticastLock();
455 }
456 }
457
458 /**
459 * Take or release the lock based on updated internal state.
460 *
461 * This determines whether the lock needs to be held based on
462 * {@link #mWifiLockRequiredNetworks}, {@link #mRunningAppActiveUids} and
463 * {@link ClientInfo#mClientRequests}, so it must be called after any of the these have been
464 * updated.
465 */
466 private void updateMulticastLock() {
467 final int needsLockUid = getMulticastLockNeededUid();
468 if (needsLockUid >= 0 && mHeldMulticastLock == null) {
469 final WifiManager wm = mContext.getSystemService(WifiManager.class);
470 if (wm == null) {
471 Log.wtf(TAG, "Got a TRANSPORT_WIFI network without WifiManager");
472 return;
473 }
474 mHeldMulticastLock = wm.createMulticastLock(TAG);
475 mHeldMulticastLock.acquire();
476 mServiceLogs.log("Taking multicast lock for uid " + needsLockUid);
477 } else if (needsLockUid < 0 && mHeldMulticastLock != null) {
478 mHeldMulticastLock.release();
479 mHeldMulticastLock = null;
480 mServiceLogs.log("Released multicast lock");
481 }
482 }
483
484 /**
485 * @return The UID of an app requiring the multicast lock, or -1 if none.
486 */
487 private int getMulticastLockNeededUid() {
488 if (mWifiLockRequiredNetworks.size() == 0) {
489 // Return early if NSD is not active, or not on any relevant network
490 return -1;
491 }
Paul Hud44e1b72023-06-16 02:07:42 +0000492 for (int i = 0; i < mTransactionIdToClientInfoMap.size(); i++) {
493 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.valueAt(i);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900494 if (!mRunningAppActiveUids.contains(clientInfo.mUid)) {
495 // Ignore non-active UIDs
496 continue;
497 }
498
499 if (clientInfo.hasAnyJavaBackendRequestForNetworks(mWifiLockRequiredNetworks)) {
500 return clientInfo.mUid;
501 }
502 }
503 return -1;
504 }
505
Paul Hu019621e2023-01-13 23:26:49 +0800506 /**
507 * Data class of mdns service callback information.
508 */
509 private static class MdnsEvent {
Paul Hud44e1b72023-06-16 02:07:42 +0000510 final int mClientRequestId;
Paul Hubad6fe92023-07-24 21:25:22 +0800511 @Nullable
Paul Hu019621e2023-01-13 23:26:49 +0800512 final MdnsServiceInfo mMdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000513 final boolean mIsServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800514
Paul Hubad6fe92023-07-24 21:25:22 +0800515 MdnsEvent(int clientRequestId) {
516 this(clientRequestId, null /* mdnsServiceInfo */, false /* isServiceFromCache */);
517 }
518
519 MdnsEvent(int clientRequestId, @Nullable MdnsServiceInfo mdnsServiceInfo) {
Paul Hua6bc4632023-06-26 01:18:29 +0000520 this(clientRequestId, mdnsServiceInfo, false /* isServiceFromCache */);
521 }
522
Paul Hubad6fe92023-07-24 21:25:22 +0800523 MdnsEvent(int clientRequestId, @Nullable MdnsServiceInfo mdnsServiceInfo,
Paul Hua6bc4632023-06-26 01:18:29 +0000524 boolean isServiceFromCache) {
Paul Hud44e1b72023-06-16 02:07:42 +0000525 mClientRequestId = clientRequestId;
Paul Hu019621e2023-01-13 23:26:49 +0800526 mMdnsServiceInfo = mdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000527 mIsServiceFromCache = isServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800528 }
529 }
530
Paul Hu77c11182023-10-23 16:17:32 +0800531 // TODO: Use a Handler instead of a StateMachine since there are no state changes.
Irfan Sheriff75006652012-04-17 23:15:29 -0700532 private class NsdStateMachine extends StateMachine {
533
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700534 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700535
536 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700537 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900538 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700539 }
540
Luke Huang92860f92021-06-23 06:29:30 +0000541 private void maybeStartDaemon() {
Paul Hu4a87ed42024-01-10 08:58:30 +0000542 if (mIsDaemonStarted) {
543 if (DBG) Log.d(TAG, "Daemon is already started.");
Ken Chen80c9f6f2023-11-15 18:24:54 +0800544 return;
545 }
546
Paul Hu4a87ed42024-01-10 08:58:30 +0000547 if (mMDnsManager == null) {
548 Log.wtf(TAG, "maybeStartDaemon: mMDnsManager is null");
paulhu2b9ed952022-02-10 21:58:32 +0800549 return;
550 }
551 mMDnsManager.registerEventListener(mMDnsEventCallback);
552 mMDnsManager.startDaemon();
553 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000554 maybeScheduleStop();
Paul Hub2e67d32023-04-18 05:50:14 +0000555 mServiceLogs.log("Start mdns_responder daemon");
Luke Huang05298582021-06-13 16:52:05 +0000556 }
557
paulhu2b9ed952022-02-10 21:58:32 +0800558 private void maybeStopDaemon() {
Paul Hu4a87ed42024-01-10 08:58:30 +0000559 if (!mIsDaemonStarted) {
560 if (DBG) Log.d(TAG, "Daemon has not been started.");
Ken Chen80c9f6f2023-11-15 18:24:54 +0800561 return;
562 }
563
Paul Hu4a87ed42024-01-10 08:58:30 +0000564 if (mMDnsManager == null) {
565 Log.wtf(TAG, "maybeStopDaemon: mMDnsManager is null");
paulhu2b9ed952022-02-10 21:58:32 +0800566 return;
567 }
568 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
569 mMDnsManager.stopDaemon();
570 mIsDaemonStarted = false;
Paul Hub2e67d32023-04-18 05:50:14 +0000571 mServiceLogs.log("Stop mdns_responder daemon");
paulhu2b9ed952022-02-10 21:58:32 +0800572 }
573
Luke Huang92860f92021-06-23 06:29:30 +0000574 private boolean isAnyRequestActive() {
Paul Hud44e1b72023-06-16 02:07:42 +0000575 return mTransactionIdToClientInfoMap.size() != 0;
Luke Huang92860f92021-06-23 06:29:30 +0000576 }
577
578 private void scheduleStop() {
579 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
580 }
581 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800582 // The native daemon should stay alive and can't be cleanup
583 // if any legacy client connected.
584 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000585 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000586 }
587 }
588
Luke Huang92860f92021-06-23 06:29:30 +0000589 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000590 this.removeMessages(NsdManager.DAEMON_CLEANUP);
591 }
592
Paul Hu23fa2022023-01-13 22:57:24 +0800593 private void maybeStartMonitoringSockets() {
594 if (mIsMonitoringSocketsStarted) {
595 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
596 return;
597 }
598
599 mMdnsSocketProvider.startMonitoringSockets();
600 mIsMonitoringSocketsStarted = true;
601 }
602
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900603 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
604 if (!mIsMonitoringSocketsStarted) return;
605 if (isAnyRequestActive()) return;
606
Paul Hu58f20602023-02-18 11:41:07 +0800607 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800608 mIsMonitoringSocketsStarted = false;
609 }
610
Hugo Benichi803a2f02017-04-24 11:35:06 +0900611 NsdStateMachine(String name, Handler handler) {
612 super(name, handler);
Paul Hu77c11182023-10-23 16:17:32 +0800613 addState(mEnabledState);
paulhu5568f452021-11-30 13:31:29 +0800614 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900615 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700616 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700617 }
618
Irfan Sheriff75006652012-04-17 23:15:29 -0700619 class EnabledState extends State {
620 @Override
621 public void enter() {
622 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700623 }
624
625 @Override
626 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000627 // TODO: it is incorrect to stop the daemon without expunging all requests
628 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000629 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700630 }
631
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700632 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900633 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800634 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700635 return true;
636 }
637 return false;
638 }
639
Paul Hu508a0122023-09-11 15:31:33 +0800640 private ClientRequest storeLegacyRequestMap(int clientRequestId, int transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +0000641 ClientInfo clientInfo, int what, long startTimeMs) {
Paul Hu508a0122023-09-11 15:31:33 +0800642 final LegacyClientRequest request =
643 new LegacyClientRequest(transactionId, what, startTimeMs);
644 clientInfo.mClientRequests.put(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000645 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000646 // Remove the cleanup event because here comes a new request.
647 cancelStop();
Paul Hu508a0122023-09-11 15:31:33 +0800648 return request;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700649 }
650
Paul Hud44e1b72023-06-16 02:07:42 +0000651 private void storeAdvertiserRequestMap(int clientRequestId, int transactionId,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900652 ClientInfo clientInfo, @Nullable Network requestedNetwork) {
Paul Hu777ed052023-06-19 13:35:15 +0000653 clientInfo.mClientRequests.put(clientRequestId, new AdvertiserClientRequest(
Paul Hu812e9212023-06-20 06:24:53 +0000654 transactionId, requestedNetwork, mClock.elapsedRealtime()));
Paul Hud44e1b72023-06-16 02:07:42 +0000655 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900656 updateMulticastLock();
Paul Hu23fa2022023-01-13 22:57:24 +0800657 }
658
Paul Hud44e1b72023-06-16 02:07:42 +0000659 private void removeRequestMap(
660 int clientRequestId, int transactionId, ClientInfo clientInfo) {
661 final ClientRequest existing = clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900662 if (existing == null) return;
Paul Hud44e1b72023-06-16 02:07:42 +0000663 clientInfo.mClientRequests.remove(clientRequestId);
664 mTransactionIdToClientInfoMap.remove(transactionId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900665
666 if (existing instanceof LegacyClientRequest) {
667 maybeScheduleStop();
668 } else {
669 maybeStopMonitoringSocketsIfNoActiveRequest();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900670 updateMulticastLock();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900671 }
672 }
673
Paul Hu508a0122023-09-11 15:31:33 +0800674 private ClientRequest storeDiscoveryManagerRequestMap(int clientRequestId,
675 int transactionId, MdnsListener listener, ClientInfo clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900676 @Nullable Network requestedNetwork) {
Paul Hu508a0122023-09-11 15:31:33 +0800677 final DiscoveryManagerRequest request = new DiscoveryManagerRequest(transactionId,
678 listener, requestedNetwork, mClock.elapsedRealtime());
679 clientInfo.mClientRequests.put(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000680 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900681 updateMulticastLock();
Paul Hu508a0122023-09-11 15:31:33 +0800682 return request;
Paul Hu23fa2022023-01-13 22:57:24 +0800683 }
684
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900685 /**
686 * Truncate a service name to up to 63 UTF-8 bytes.
687 *
688 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
689 * names used in registerService follows historical behavior (see mdnsresponder
690 * handle_regservice_request).
691 */
692 @NonNull
693 private String truncateServiceName(@NonNull String originalName) {
Yuyang Huangde802c82023-05-02 17:14:22 +0900694 return MdnsUtils.truncateServiceName(originalName, MAX_LABEL_LENGTH);
Paul Hu23fa2022023-01-13 22:57:24 +0800695 }
696
Paul Hud44e1b72023-06-16 02:07:42 +0000697 private void stopDiscoveryManagerRequest(ClientRequest request, int clientRequestId,
698 int transactionId, ClientInfo clientInfo) {
Paul Hue4f5f252023-02-16 21:13:47 +0800699 clientInfo.unregisterMdnsListenerFromRequest(request);
Paul Hud44e1b72023-06-16 02:07:42 +0000700 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hue4f5f252023-02-16 21:13:47 +0800701 }
702
Paul Hu77c11182023-10-23 16:17:32 +0800703 private ClientInfo getClientInfoForReply(Message msg) {
704 final ListenerArgs args = (ListenerArgs) msg.obj;
705 return mClients.get(args.connector);
706 }
707
Kangping Dong5af24b62023-12-10 21:41:16 +0800708 /**
709 * Returns {@code false} if {@code subtypes} exceeds the maximum number limit or
710 * contains invalid subtype label.
711 */
712 private boolean checkSubtypeLabels(Set<String> subtypes) {
713 if (subtypes.size() > MAX_SUBTYPE_COUNT) {
714 mServiceLogs.e(
715 "Too many subtypes: " + subtypes.size() + " (max = "
716 + MAX_SUBTYPE_COUNT + ")");
717 return false;
718 }
719
720 for (String subtype : subtypes) {
721 if (!checkSubtypeLabel(subtype)) {
722 mServiceLogs.e("Subtype " + subtype + " is invalid");
723 return false;
724 }
725 }
726 return true;
727 }
728
729 private Set<String> dedupSubtypeLabels(Collection<String> subtypes) {
730 final Map<String, String> subtypeMap = new LinkedHashMap<>(subtypes.size());
731 for (String subtype : subtypes) {
732 subtypeMap.put(MdnsUtils.toDnsLowerCase(subtype), subtype);
733 }
734 return new ArraySet<>(subtypeMap.values());
735 }
736
Irfan Sheriff75006652012-04-17 23:15:29 -0700737 @Override
738 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900739 final ClientInfo clientInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000740 final int transactionId;
741 final int clientRequestId = msg.arg2;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900742 final OffloadEngineInfo offloadEngineInfo;
Irfan Sheriff75006652012-04-17 23:15:29 -0700743 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800744 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800745 if (DBG) Log.d(TAG, "Discover services");
Kangping Dong1f1a3792023-12-10 22:05:04 +0800746 final DiscoveryArgs discoveryArgs = (DiscoveryArgs) msg.obj;
747 clientInfo = mClients.get(discoveryArgs.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000748 // If the binder death notification for a INsdManagerCallback was received
749 // before any calls are received by NsdService, the clientInfo would be
750 // cleared and cause NPE. Add a null check here to prevent this corner case.
751 if (clientInfo == null) {
752 Log.e(TAG, "Unknown connector in discovery");
753 break;
754 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700755
756 if (requestLimitReached(clientInfo)) {
Paul Hu508a0122023-09-11 15:31:33 +0800757 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
758 NsdManager.FAILURE_MAX_LIMIT, true /* isLegacy */);
Irfan Sheriff75006652012-04-17 23:15:29 -0700759 break;
760 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700761
Kangping Dong1f1a3792023-12-10 22:05:04 +0800762 final DiscoveryRequest discoveryRequest = discoveryArgs.discoveryRequest;
Paul Hud44e1b72023-06-16 02:07:42 +0000763 transactionId = getUniqueId();
Yuyang Huang170d42f2023-12-09 15:26:16 +0900764 final Pair<String, List<String>> typeAndSubtype =
Kangping Dong1f1a3792023-12-10 22:05:04 +0800765 parseTypeAndSubtype(discoveryRequest.getServiceType());
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900766 final String serviceType = typeAndSubtype == null
767 ? null : typeAndSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800768 if (clientInfo.mUseJavaBackend
769 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900770 || useDiscoveryManagerForType(serviceType)) {
Yuyang Huang170d42f2023-12-09 15:26:16 +0900771 if (serviceType == null || typeAndSubtype.second.size() > 1) {
Paul Hu508a0122023-09-11 15:31:33 +0800772 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
773 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Paul Hu23fa2022023-01-13 22:57:24 +0800774 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700775 }
Paul Hu23fa2022023-01-13 22:57:24 +0800776
Kangping Dong1f1a3792023-12-10 22:05:04 +0800777 String subtype = discoveryRequest.getSubtype();
778 if (subtype == null && !typeAndSubtype.second.isEmpty()) {
779 subtype = typeAndSubtype.second.get(0);
780 }
781
782 if (subtype != null && !checkSubtypeLabel(subtype)) {
783 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
784 NsdManager.FAILURE_BAD_PARAMETERS, false /* isLegacy */);
785 break;
786 }
787
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900788 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800789 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +0000790 final MdnsListener listener = new DiscoveryListener(clientRequestId,
Kangping Dong97b2adc2024-01-11 16:00:37 +0800791 transactionId, listenServiceType);
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900792 final MdnsSearchOptions.Builder optionsBuilder =
793 MdnsSearchOptions.newBuilder()
Kangping Dong1f1a3792023-12-10 22:05:04 +0800794 .setNetwork(discoveryRequest.getNetwork())
Yuyang Huangff963222023-06-01 18:42:42 +0900795 .setRemoveExpiredService(true)
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900796 .setIsPassiveMode(true);
Kangping Dong1f1a3792023-12-10 22:05:04 +0800797
798 if (subtype != null) {
799 // checkSubtypeLabels() ensures that subtypes start with '_' but
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900800 // MdnsSearchOptions expects the underscore to not be present.
Kangping Dong1f1a3792023-12-10 22:05:04 +0800801 optionsBuilder.addSubtype(subtype.substring(1));
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900802 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900803 mMdnsDiscoveryManager.registerListener(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900804 listenServiceType, listener, optionsBuilder.build());
Paul Hu508a0122023-09-11 15:31:33 +0800805 final ClientRequest request = storeDiscoveryManagerRequestMap(
806 clientRequestId, transactionId, listener, clientInfo,
Kangping Dong1f1a3792023-12-10 22:05:04 +0800807 discoveryRequest.getNetwork());
808 clientInfo.onDiscoverServicesStarted(
809 clientRequestId, discoveryRequest, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000810 clientInfo.log("Register a DiscoveryListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +0000811 + " for service type:" + listenServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700812 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800813 maybeStartDaemon();
Kangping Dong1f1a3792023-12-10 22:05:04 +0800814 if (discoverServices(transactionId, discoveryRequest)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800815 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +0000816 Log.d(TAG, "Discover " + msg.arg2 + " " + transactionId
Kangping Dong1f1a3792023-12-10 22:05:04 +0800817 + discoveryRequest.getServiceType());
Paul Hu23fa2022023-01-13 22:57:24 +0800818 }
Paul Hu508a0122023-09-11 15:31:33 +0800819 final ClientRequest request = storeLegacyRequestMap(clientRequestId,
820 transactionId, clientInfo, msg.what,
821 mClock.elapsedRealtime());
Paul Hu812e9212023-06-20 06:24:53 +0000822 clientInfo.onDiscoverServicesStarted(
Kangping Dong1f1a3792023-12-10 22:05:04 +0800823 clientRequestId, discoveryRequest, request);
Paul Hu23fa2022023-01-13 22:57:24 +0800824 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000825 stopServiceDiscovery(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800826 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
827 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Paul Hu23fa2022023-01-13 22:57:24 +0800828 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700829 }
830 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800831 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900832 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800833 if (DBG) Log.d(TAG, "Stop service discovery");
Yuyang Huang86d083f2023-12-12 19:56:41 +0900834 final ListenerArgs args = (ListenerArgs) msg.obj;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900835 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000836 // If the binder death notification for a INsdManagerCallback was received
837 // before any calls are received by NsdService, the clientInfo would be
838 // cleared and cause NPE. Add a null check here to prevent this corner case.
839 if (clientInfo == null) {
840 Log.e(TAG, "Unknown connector in stop discovery");
841 break;
842 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700843
Paul Hud44e1b72023-06-16 02:07:42 +0000844 final ClientRequest request =
845 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900846 if (request == null) {
847 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700848 break;
849 }
Paul Hud44e1b72023-06-16 02:07:42 +0000850 transactionId = request.mTransactionId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900851 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
852 // point, so this needs to check the type of the original request to
853 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900854 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +0000855 stopDiscoveryManagerRequest(
856 request, clientRequestId, transactionId, clientInfo);
Paul Hu812e9212023-06-20 06:24:53 +0000857 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000858 clientInfo.log("Unregister the DiscoveryListener " + transactionId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700859 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000860 removeRequestMap(clientRequestId, transactionId, clientInfo);
861 if (stopServiceDiscovery(transactionId)) {
Paul Hu812e9212023-06-20 06:24:53 +0000862 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hu23fa2022023-01-13 22:57:24 +0800863 } else {
864 clientInfo.onStopDiscoveryFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000865 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu23fa2022023-01-13 22:57:24 +0800866 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700867 }
868 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900869 }
870 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800871 if (DBG) Log.d(TAG, "Register service");
Yuyang Huang86d083f2023-12-12 19:56:41 +0900872 final AdvertisingArgs args = (AdvertisingArgs) msg.obj;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900873 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000874 // If the binder death notification for a INsdManagerCallback was received
875 // before any calls are received by NsdService, the clientInfo would be
876 // cleared and cause NPE. Add a null check here to prevent this corner case.
877 if (clientInfo == null) {
878 Log.e(TAG, "Unknown connector in registration");
879 break;
880 }
881
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700882 if (requestLimitReached(clientInfo)) {
Paul Hu508a0122023-09-11 15:31:33 +0800883 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
884 NsdManager.FAILURE_MAX_LIMIT, true /* isLegacy */);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700885 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700886 }
Yuyang Huang86d083f2023-12-12 19:56:41 +0900887 final AdvertisingRequest advertisingRequest = args.advertisingRequest;
888 if (advertisingRequest == null) {
889 Log.e(TAG, "Unknown advertisingRequest in registration");
890 break;
891 }
892 final NsdServiceInfo serviceInfo = advertisingRequest.getServiceInfo();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900893 final String serviceType = serviceInfo.getServiceType();
Yuyang Huang170d42f2023-12-09 15:26:16 +0900894 final Pair<String, List<String>> typeSubtype = parseTypeAndSubtype(
895 serviceType);
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900896 final String registerServiceType = typeSubtype == null
897 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800898 if (clientInfo.mUseJavaBackend
899 || mDeps.isMdnsAdvertiserEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900900 || useAdvertiserForType(registerServiceType)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900901 if (registerServiceType == null) {
902 Log.e(TAG, "Invalid service type: " + serviceType);
Paul Hu508a0122023-09-11 15:31:33 +0800903 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
904 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900905 break;
906 }
Yuyang Huang86d083f2023-12-12 19:56:41 +0900907 boolean isUpdateOnly = (advertisingRequest.getAdvertisingConfig()
908 & AdvertisingRequest.NSD_ADVERTISING_UPDATE_ONLY) > 0;
909 // If it is an update request, then reuse the old transactionId
910 if (isUpdateOnly) {
911 final ClientRequest existingClientRequest =
912 clientInfo.mClientRequests.get(clientRequestId);
913 if (existingClientRequest == null) {
914 Log.e(TAG, "Invalid update on requestId: " + clientRequestId);
915 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
916 NsdManager.FAILURE_INTERNAL_ERROR,
917 false /* isLegacy */);
918 break;
919 }
920 transactionId = existingClientRequest.mTransactionId;
921 } else {
922 transactionId = getUniqueId();
923 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900924 serviceInfo.setServiceType(registerServiceType);
925 serviceInfo.setServiceName(truncateServiceName(
926 serviceInfo.getServiceName()));
927
Kangping Dong5af24b62023-12-10 21:41:16 +0800928 Set<String> subtypes = new ArraySet<>(serviceInfo.getSubtypes());
Yuyang Huang170d42f2023-12-09 15:26:16 +0900929 for (String subType: typeSubtype.second) {
930 if (!TextUtils.isEmpty(subType)) {
931 subtypes.add(subType);
932 }
Kangping Dong5af24b62023-12-10 21:41:16 +0800933 }
Kangping Dong5af24b62023-12-10 21:41:16 +0800934 subtypes = dedupSubtypeLabels(subtypes);
935
936 if (!checkSubtypeLabels(subtypes)) {
937 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
938 NsdManager.FAILURE_BAD_PARAMETERS, false /* isLegacy */);
939 break;
940 }
941
942 serviceInfo.setSubtypes(subtypes);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900943 maybeStartMonitoringSockets();
Yuyang Huang86d083f2023-12-12 19:56:41 +0900944 final MdnsAdvertisingOptions mdnsAdvertisingOptions =
945 MdnsAdvertisingOptions.newBuilder().setIsOnlyUpdate(
946 isUpdateOnly).build();
Yuyang Huange5cba9c2023-11-02 18:05:47 +0900947 mAdvertiser.addOrUpdateService(transactionId, serviceInfo,
Yuyang Huang86d083f2023-12-12 19:56:41 +0900948 mdnsAdvertisingOptions);
Paul Hud44e1b72023-06-16 02:07:42 +0000949 storeAdvertiserRequestMap(clientRequestId, transactionId, clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900950 serviceInfo.getNetwork());
Irfan Sheriff75006652012-04-17 23:15:29 -0700951 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900952 maybeStartDaemon();
Yuyang Huang86d083f2023-12-12 19:56:41 +0900953 transactionId = getUniqueId();
Paul Hud44e1b72023-06-16 02:07:42 +0000954 if (registerService(transactionId, serviceInfo)) {
955 if (DBG) {
956 Log.d(TAG, "Register " + clientRequestId
957 + " " + transactionId);
958 }
Paul Hua6bc4632023-06-26 01:18:29 +0000959 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
960 msg.what, mClock.elapsedRealtime());
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900961 // Return success after mDns reports success
962 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000963 unregisterService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800964 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
965 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900966 }
967
Irfan Sheriff75006652012-04-17 23:15:29 -0700968 }
969 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900970 }
971 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800972 if (DBG) Log.d(TAG, "unregister service");
Yuyang Huang86d083f2023-12-12 19:56:41 +0900973 final ListenerArgs args = (ListenerArgs) msg.obj;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900974 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000975 // If the binder death notification for a INsdManagerCallback was received
976 // before any calls are received by NsdService, the clientInfo would be
977 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900978 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800979 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700980 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700981 }
Paul Hud44e1b72023-06-16 02:07:42 +0000982 final ClientRequest request =
983 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900984 if (request == null) {
985 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
986 break;
987 }
Paul Hud44e1b72023-06-16 02:07:42 +0000988 transactionId = request.mTransactionId;
989 removeRequestMap(clientRequestId, transactionId, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900990
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900991 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
992 // so this needs to check the type of the original request to unregister
993 // instead of looking at the flag value.
994 if (request instanceof AdvertiserClientRequest) {
Paul Hu043bcd42023-07-14 16:38:25 +0800995 final AdvertiserMetrics metrics =
996 mAdvertiser.getAdvertiserMetrics(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +0000997 mAdvertiser.removeService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800998 clientInfo.onUnregisterServiceSucceeded(
999 clientRequestId, request, metrics);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001000 } else {
Paul Hud44e1b72023-06-16 02:07:42 +00001001 if (unregisterService(transactionId)) {
Paul Hu508a0122023-09-11 15:31:33 +08001002 clientInfo.onUnregisterServiceSucceeded(clientRequestId, request,
Paul Hu043bcd42023-07-14 16:38:25 +08001003 new AdvertiserMetrics(NO_PACKET /* repliedRequestsCount */,
1004 NO_PACKET /* sentPacketCount */,
1005 0 /* conflictDuringProbingCount */,
1006 0 /* conflictAfterProbingCount */));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001007 } else {
1008 clientInfo.onUnregisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001009 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001010 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001011 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001012 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001013 }
Paul Hu75069ed2023-01-14 00:31:09 +08001014 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +08001015 if (DBG) Log.d(TAG, "Resolve service");
Yuyang Huang86d083f2023-12-12 19:56:41 +09001016 final ListenerArgs args = (ListenerArgs) msg.obj;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001017 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +00001018 // If the binder death notification for a INsdManagerCallback was received
1019 // before any calls are received by NsdService, the clientInfo would be
1020 // cleared and cause NPE. Add a null check here to prevent this corner case.
1021 if (clientInfo == null) {
1022 Log.e(TAG, "Unknown connector in resolution");
1023 break;
1024 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001025
Paul Hu75069ed2023-01-14 00:31:09 +08001026 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001027 transactionId = getUniqueId();
Yuyang Huang170d42f2023-12-09 15:26:16 +09001028 final Pair<String, List<String>> typeSubtype =
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001029 parseTypeAndSubtype(info.getServiceType());
1030 final String serviceType = typeSubtype == null
1031 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001032 if (clientInfo.mUseJavaBackend
1033 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001034 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +08001035 if (serviceType == null) {
Paul Hu508a0122023-09-11 15:31:33 +08001036 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
1037 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +08001038 break;
1039 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001040 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +08001041
1042 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001043 final MdnsListener listener = new ResolutionListener(clientRequestId,
Kangping Dong97b2adc2024-01-11 16:00:37 +08001044 transactionId, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +08001045 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1046 .setNetwork(info.getNetwork())
1047 .setIsPassiveMode(true)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +09001048 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001049 .setRemoveExpiredService(true)
Paul Hu75069ed2023-01-14 00:31:09 +08001050 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001051 mMdnsDiscoveryManager.registerListener(
1052 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001053 storeDiscoveryManagerRequestMap(clientRequestId, transactionId,
1054 listener, clientInfo, info.getNetwork());
1055 clientInfo.log("Register a ResolutionListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001056 + " for service type:" + resolveServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -07001057 } else {
Paul Hu75069ed2023-01-14 00:31:09 +08001058 if (clientInfo.mResolvedService != null) {
Paul Hu508a0122023-09-11 15:31:33 +08001059 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
1060 NsdManager.FAILURE_ALREADY_ACTIVE, true /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +08001061 break;
1062 }
1063
1064 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +00001065 if (resolveService(transactionId, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +08001066 clientInfo.mResolvedService = new NsdServiceInfo();
Paul Hua6bc4632023-06-26 01:18:29 +00001067 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
1068 msg.what, mClock.elapsedRealtime());
Paul Hu75069ed2023-01-14 00:31:09 +08001069 } else {
Paul Hu508a0122023-09-11 15:31:33 +08001070 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
1071 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +08001072 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001073 }
1074 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001075 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001076 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +00001077 if (DBG) Log.d(TAG, "Stop service resolution");
Yuyang Huang86d083f2023-12-12 19:56:41 +09001078 final ListenerArgs args = (ListenerArgs) msg.obj;
Paul Hub58deb72022-12-26 09:24:42 +00001079 clientInfo = mClients.get(args.connector);
1080 // If the binder death notification for a INsdManagerCallback was received
1081 // before any calls are received by NsdService, the clientInfo would be
1082 // cleared and cause NPE. Add a null check here to prevent this corner case.
1083 if (clientInfo == null) {
1084 Log.e(TAG, "Unknown connector in stop resolution");
1085 break;
1086 }
1087
Paul Hud44e1b72023-06-16 02:07:42 +00001088 final ClientRequest request =
1089 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001090 if (request == null) {
1091 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
1092 break;
1093 }
Paul Hud44e1b72023-06-16 02:07:42 +00001094 transactionId = request.mTransactionId;
Paul Hue4f5f252023-02-16 21:13:47 +08001095 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
1096 // point, so this needs to check the type of the original request to
1097 // unregister instead of looking at the flag value.
1098 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001099 stopDiscoveryManagerRequest(
1100 request, clientRequestId, transactionId, clientInfo);
Paul Hu60149052023-07-31 14:26:08 +08001101 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001102 clientInfo.log("Unregister the ResolutionListener " + transactionId);
Paul Hub58deb72022-12-26 09:24:42 +00001103 } else {
Paul Hud44e1b72023-06-16 02:07:42 +00001104 removeRequestMap(clientRequestId, transactionId, clientInfo);
1105 if (stopResolveService(transactionId)) {
Paul Hu60149052023-07-31 14:26:08 +08001106 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hue4f5f252023-02-16 21:13:47 +08001107 } else {
1108 clientInfo.onStopResolutionFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001109 clientRequestId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hue4f5f252023-02-16 21:13:47 +08001110 }
1111 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +00001112 }
Paul Hub58deb72022-12-26 09:24:42 +00001113 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001114 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001115 case NsdManager.REGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001116 if (DBG) Log.d(TAG, "Register a service callback");
Yuyang Huang86d083f2023-12-12 19:56:41 +09001117 final ListenerArgs args = (ListenerArgs) msg.obj;
Paul Hu18aeccc2022-12-27 08:48:48 +00001118 clientInfo = mClients.get(args.connector);
1119 // If the binder death notification for a INsdManagerCallback was received
1120 // before any calls are received by NsdService, the clientInfo would be
1121 // cleared and cause NPE. Add a null check here to prevent this corner case.
1122 if (clientInfo == null) {
1123 Log.e(TAG, "Unknown connector in callback registration");
1124 break;
1125 }
1126
Paul Hu30bd70d2023-02-07 13:20:56 +00001127 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001128 transactionId = getUniqueId();
Yuyang Huang170d42f2023-12-09 15:26:16 +09001129 final Pair<String, List<String>> typeAndSubtype =
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001130 parseTypeAndSubtype(info.getServiceType());
1131 final String serviceType = typeAndSubtype == null
1132 ? null : typeAndSubtype.first;
Paul Hu30bd70d2023-02-07 13:20:56 +00001133 if (serviceType == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001134 clientInfo.onServiceInfoCallbackRegistrationFailed(clientRequestId,
Paul Hu30bd70d2023-02-07 13:20:56 +00001135 NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +00001136 break;
1137 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001138 final String resolveServiceType = serviceType + ".local";
Paul Hu18aeccc2022-12-27 08:48:48 +00001139
Paul Hu30bd70d2023-02-07 13:20:56 +00001140 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001141 final MdnsListener listener = new ServiceInfoListener(clientRequestId,
Kangping Dong97b2adc2024-01-11 16:00:37 +08001142 transactionId, resolveServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +00001143 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1144 .setNetwork(info.getNetwork())
1145 .setIsPassiveMode(true)
1146 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001147 .setRemoveExpiredService(true)
Paul Hu30bd70d2023-02-07 13:20:56 +00001148 .build();
1149 mMdnsDiscoveryManager.registerListener(
1150 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001151 storeDiscoveryManagerRequestMap(clientRequestId, transactionId, listener,
1152 clientInfo, info.getNetwork());
Paul Huddce5912023-08-01 10:26:49 +08001153 clientInfo.onServiceInfoCallbackRegistered(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00001154 clientInfo.log("Register a ServiceInfoListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001155 + " for service type:" + resolveServiceType);
Paul Hu18aeccc2022-12-27 08:48:48 +00001156 break;
Paul Hu30bd70d2023-02-07 13:20:56 +00001157 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001158 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001159 if (DBG) Log.d(TAG, "Unregister a service callback");
Yuyang Huang86d083f2023-12-12 19:56:41 +09001160 final ListenerArgs args = (ListenerArgs) msg.obj;
Paul Hu18aeccc2022-12-27 08:48:48 +00001161 clientInfo = mClients.get(args.connector);
1162 // If the binder death notification for a INsdManagerCallback was received
1163 // before any calls are received by NsdService, the clientInfo would be
1164 // cleared and cause NPE. Add a null check here to prevent this corner case.
1165 if (clientInfo == null) {
1166 Log.e(TAG, "Unknown connector in callback unregistration");
1167 break;
1168 }
1169
Paul Hud44e1b72023-06-16 02:07:42 +00001170 final ClientRequest request =
1171 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001172 if (request == null) {
Paul Hu30bd70d2023-02-07 13:20:56 +00001173 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE_CALLBACK");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001174 break;
1175 }
Paul Hud44e1b72023-06-16 02:07:42 +00001176 transactionId = request.mTransactionId;
Paul Hu30bd70d2023-02-07 13:20:56 +00001177 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001178 stopDiscoveryManagerRequest(
1179 request, clientRequestId, transactionId, clientInfo);
Paul Huddce5912023-08-01 10:26:49 +08001180 clientInfo.onServiceInfoCallbackUnregistered(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001181 clientInfo.log("Unregister the ServiceInfoListener " + transactionId);
Paul Hu18aeccc2022-12-27 08:48:48 +00001182 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001183 loge("Unregister failed with non-DiscoveryManagerRequest.");
Paul Hu18aeccc2022-12-27 08:48:48 +00001184 }
Paul Hu18aeccc2022-12-27 08:48:48 +00001185 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001186 }
paulhu2b9ed952022-02-10 21:58:32 +08001187 case MDNS_SERVICE_EVENT:
1188 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +09001189 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001190 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001191 break;
Paul Hu019621e2023-01-13 23:26:49 +08001192 case MDNS_DISCOVERY_MANAGER_EVENT:
1193 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
1194 return NOT_HANDLED;
1195 }
1196 break;
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001197 case NsdManager.REGISTER_OFFLOAD_ENGINE:
1198 offloadEngineInfo = (OffloadEngineInfo) msg.obj;
1199 // TODO: Limits the number of registrations created by a given class.
1200 mOffloadEngines.register(offloadEngineInfo.mOffloadEngine,
1201 offloadEngineInfo);
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001202 sendAllOffloadServiceInfos(offloadEngineInfo);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001203 break;
1204 case NsdManager.UNREGISTER_OFFLOAD_ENGINE:
1205 mOffloadEngines.unregister((IOffloadEngine) msg.obj);
1206 break;
Paul Hu77c11182023-10-23 16:17:32 +08001207 case NsdManager.REGISTER_CLIENT:
1208 final ConnectorArgs arg = (ConnectorArgs) msg.obj;
1209 final INsdManagerCallback cb = arg.callback;
1210 try {
1211 cb.asBinder().linkToDeath(arg.connector, 0);
1212 final String tag = "Client" + arg.uid + "-" + mClientNumberId++;
1213 final NetworkNsdReportedMetrics metrics =
1214 mDeps.makeNetworkNsdReportedMetrics(
1215 (int) mClock.elapsedRealtime());
1216 clientInfo = new ClientInfo(cb, arg.uid, arg.useJavaBackend,
1217 mServiceLogs.forSubComponent(tag), metrics);
1218 mClients.put(arg.connector, clientInfo);
1219 } catch (RemoteException e) {
1220 Log.w(TAG, "Client request id " + clientRequestId
1221 + " has already died");
1222 }
1223 break;
1224 case NsdManager.UNREGISTER_CLIENT:
1225 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
1226 clientInfo = mClients.remove(connector);
1227 if (clientInfo != null) {
1228 clientInfo.expungeAllRequests();
1229 if (clientInfo.isPreSClient()) {
1230 mLegacyClientCount -= 1;
1231 }
1232 }
1233 maybeStopMonitoringSocketsIfNoActiveRequest();
1234 maybeScheduleStop();
1235 break;
1236 case NsdManager.DAEMON_CLEANUP:
1237 maybeStopDaemon();
1238 break;
1239 // This event should be only sent by the legacy (target SDK < S) clients.
1240 // Mark the sending client as legacy.
1241 case NsdManager.DAEMON_STARTUP:
1242 clientInfo = getClientInfoForReply(msg);
1243 if (clientInfo != null) {
1244 cancelStop();
1245 clientInfo.setPreSClient();
1246 mLegacyClientCount += 1;
1247 maybeStartDaemon();
1248 }
1249 break;
Irfan Sheriff75006652012-04-17 23:15:29 -07001250 default:
Paul Hu77c11182023-10-23 16:17:32 +08001251 Log.wtf(TAG, "Unhandled " + msg);
Hugo Benichif0c84092017-04-05 14:43:29 +09001252 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001253 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001254 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001255 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001256
Paul Hud44e1b72023-06-16 02:07:42 +00001257 private boolean handleMDnsServiceEvent(int code, int transactionId, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001258 NsdServiceInfo servInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001259 ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001260 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001261 Log.e(TAG, String.format(
1262 "transactionId %d for %d has no client mapping", transactionId, code));
Hugo Benichif0c84092017-04-05 14:43:29 +09001263 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001264 }
1265
1266 /* This goes in response as msg.arg2 */
Paul Hud44e1b72023-06-16 02:07:42 +00001267 int clientRequestId = clientInfo.getClientRequestId(transactionId);
1268 if (clientRequestId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -07001269 // This can happen because of race conditions. For example,
1270 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
1271 // and we may get in this situation.
Paul Hud44e1b72023-06-16 02:07:42 +00001272 Log.d(TAG, String.format("%d for transactionId %d that is no longer active",
1273 code, transactionId));
Hugo Benichif0c84092017-04-05 14:43:29 +09001274 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001275 }
Paul Hu812e9212023-06-20 06:24:53 +00001276 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1277 if (request == null) {
1278 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1279 return false;
1280 }
Hugo Benichi32be63d2017-04-05 14:06:11 +09001281 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00001282 Log.d(TAG, String.format(
1283 "MDns service event code:%d transactionId=%d", code, transactionId));
Hugo Benichi32be63d2017-04-05 14:06:11 +09001284 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001285 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +08001286 case IMDnsEventListener.SERVICE_FOUND: {
1287 final DiscoveryInfo info = (DiscoveryInfo) obj;
1288 final String name = info.serviceName;
1289 final String type = info.registrationType;
1290 servInfo = new NsdServiceInfo(name, type);
1291 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001292 if (foundNetId == 0L) {
1293 // Ignore services that do not have a Network: they are not usable
1294 // by apps, as they would need privileged permissions to use
1295 // interfaces that do not have an associated Network.
1296 break;
1297 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +09001298 if (foundNetId == INetd.DUMMY_NET_ID) {
1299 // Ignore services on the dummy0 interface: they are only seen when
1300 // discovering locally advertised services, and are not reachable
1301 // through that interface.
1302 break;
1303 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001304 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001305
1306 clientInfo.onServiceFound(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001307 break;
paulhu2b9ed952022-02-10 21:58:32 +08001308 }
1309 case IMDnsEventListener.SERVICE_LOST: {
1310 final DiscoveryInfo info = (DiscoveryInfo) obj;
1311 final String name = info.serviceName;
1312 final String type = info.registrationType;
1313 final int lostNetId = info.netId;
1314 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001315 // The network could be set to null (netId 0) if it was torn down when the
1316 // service is lost
1317 // TODO: avoid returning null in that case, possibly by remembering
1318 // found services on the same interface index and their network at the time
1319 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001320 clientInfo.onServiceLost(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001321 break;
paulhu2b9ed952022-02-10 21:58:32 +08001322 }
1323 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Paul Hu812e9212023-06-20 06:24:53 +00001324 clientInfo.onDiscoverServicesFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001325 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1326 transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001327 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001328 break;
paulhu2b9ed952022-02-10 21:58:32 +08001329 case IMDnsEventListener.SERVICE_REGISTERED: {
1330 final RegistrationInfo info = (RegistrationInfo) obj;
1331 final String name = info.serviceName;
1332 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Paul Hu508a0122023-09-11 15:31:33 +08001333 clientInfo.onRegisterServiceSucceeded(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001334 break;
paulhu2b9ed952022-02-10 21:58:32 +08001335 }
1336 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Paul Hu777ed052023-06-19 13:35:15 +00001337 clientInfo.onRegisterServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001338 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1339 transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001340 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001341 break;
paulhu2b9ed952022-02-10 21:58:32 +08001342 case IMDnsEventListener.SERVICE_RESOLVED: {
1343 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001344 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +08001345 final String fullName = info.serviceFullName;
1346 while (index < fullName.length() && fullName.charAt(index) != '.') {
1347 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001348 ++index;
1349 }
1350 ++index;
1351 }
paulhu2b9ed952022-02-10 21:58:32 +08001352 if (index >= fullName.length()) {
1353 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001354 break;
1355 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001356
paulhube186602022-04-12 07:18:23 +00001357 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001358 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001359 String type = rest.replace(".local.", "");
1360
Paul Hu30bd70d2023-02-07 13:20:56 +00001361 final NsdServiceInfo serviceInfo = clientInfo.mResolvedService;
Paul Hu18aeccc2022-12-27 08:48:48 +00001362 serviceInfo.setServiceName(name);
1363 serviceInfo.setServiceType(type);
1364 serviceInfo.setPort(info.port);
1365 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001366 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001367
Paul Hud44e1b72023-06-16 02:07:42 +00001368 stopResolveService(transactionId);
1369 removeRequestMap(clientRequestId, transactionId, clientInfo);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001370
Paul Hud44e1b72023-06-16 02:07:42 +00001371 final int transactionId2 = getUniqueId();
1372 if (getAddrInfo(transactionId2, info.hostname, info.interfaceIdx)) {
1373 storeLegacyRequestMap(clientRequestId, transactionId2, clientInfo,
Paul Hua6bc4632023-06-26 01:18:29 +00001374 NsdManager.RESOLVE_SERVICE, request.mStartTimeMs);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001375 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001376 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001377 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1378 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001379 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001380 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001381 }
1382 break;
paulhu2b9ed952022-02-10 21:58:32 +08001383 }
1384 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001385 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001386 stopResolveService(transactionId);
1387 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001388 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001389 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1390 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001391 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001392 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001393 break;
paulhu2b9ed952022-02-10 21:58:32 +08001394 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001395 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001396 stopGetAddrInfo(transactionId);
1397 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001398 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001399 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1400 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001401 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001402 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001403 break;
paulhu2b9ed952022-02-10 21:58:32 +08001404 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001405 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001406 final GetAddressInfo info = (GetAddressInfo) obj;
1407 final String address = info.address;
1408 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001409 InetAddress serviceHost = null;
1410 try {
paulhu2b9ed952022-02-10 21:58:32 +08001411 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001412 } catch (UnknownHostException e) {
1413 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1414 }
1415
1416 // If the resolved service is on an interface without a network, consider it
1417 // as a failure: it would not be usable by apps as they would need
1418 // privileged permissions.
Paul Hu30bd70d2023-02-07 13:20:56 +00001419 if (netId != NETID_UNSET && serviceHost != null) {
1420 clientInfo.mResolvedService.setHost(serviceHost);
1421 setServiceNetworkForCallback(clientInfo.mResolvedService,
1422 netId, info.interfaceIdx);
1423 clientInfo.onResolveServiceSucceeded(
Paul Hua6bc4632023-06-26 01:18:29 +00001424 clientRequestId, clientInfo.mResolvedService, request);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001425 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001426 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001427 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1428 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001429 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001430 }
Paul Hud44e1b72023-06-16 02:07:42 +00001431 stopGetAddrInfo(transactionId);
1432 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001433 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001434 break;
paulhu2b9ed952022-02-10 21:58:32 +08001435 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001436 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001437 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001438 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001439 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001440 }
Paul Hu019621e2023-01-13 23:26:49 +08001441
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001442 @Nullable
1443 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(
1444 final MdnsEvent event, int code) {
Paul Hu019621e2023-01-13 23:26:49 +08001445 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001446 final String[] typeArray = serviceInfo.getServiceType();
1447 final String joinedType;
1448 if (typeArray.length == 0
1449 || !typeArray[typeArray.length - 1].equals(LOCAL_DOMAIN_NAME)) {
1450 Log.wtf(TAG, "MdnsServiceInfo type does not end in .local: "
1451 + Arrays.toString(typeArray));
1452 return null;
1453 } else {
1454 joinedType = TextUtils.join(".",
1455 Arrays.copyOfRange(typeArray, 0, typeArray.length - 1));
1456 }
1457 final String serviceType;
1458 switch (code) {
1459 case NsdManager.SERVICE_FOUND:
1460 case NsdManager.SERVICE_LOST:
1461 // For consistency with historical behavior, discovered service types have
1462 // a dot at the end.
1463 serviceType = joinedType + ".";
1464 break;
1465 case RESOLVE_SERVICE_SUCCEEDED:
1466 // For consistency with historical behavior, resolved service types have
1467 // a dot at the beginning.
1468 serviceType = "." + joinedType;
1469 break;
1470 default:
1471 serviceType = joinedType;
1472 break;
1473 }
Paul Hu019621e2023-01-13 23:26:49 +08001474 final String serviceName = serviceInfo.getServiceInstanceName();
1475 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1476 final Network network = serviceInfo.getNetwork();
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001477 // In MdnsDiscoveryManagerEvent, the Network can be null which means it is a
1478 // network for Tethering interface. In other words, the network == null means the
1479 // network has netId = INetd.LOCAL_NET_ID.
Paul Hu019621e2023-01-13 23:26:49 +08001480 setServiceNetworkForCallback(
1481 servInfo,
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001482 network == null ? INetd.LOCAL_NET_ID : network.netId,
Paul Hu019621e2023-01-13 23:26:49 +08001483 serviceInfo.getInterfaceIndex());
Kangping Dong5af24b62023-12-10 21:41:16 +08001484 servInfo.setSubtypes(dedupSubtypeLabels(serviceInfo.getSubtypes()));
Paul Hu019621e2023-01-13 23:26:49 +08001485 return servInfo;
1486 }
1487
1488 private boolean handleMdnsDiscoveryManagerEvent(
1489 int transactionId, int code, Object obj) {
Paul Hud44e1b72023-06-16 02:07:42 +00001490 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Paul Hu019621e2023-01-13 23:26:49 +08001491 if (clientInfo == null) {
1492 Log.e(TAG, String.format(
1493 "id %d for %d has no client mapping", transactionId, code));
1494 return false;
1495 }
1496
1497 final MdnsEvent event = (MdnsEvent) obj;
Paul Hud44e1b72023-06-16 02:07:42 +00001498 final int clientRequestId = event.mClientRequestId;
Paul Hubad6fe92023-07-24 21:25:22 +08001499 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1500 if (request == null) {
1501 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1502 return false;
1503 }
1504
1505 // Deal with the discovery sent callback
1506 if (code == DISCOVERY_QUERY_SENT_CALLBACK) {
1507 request.onQuerySent();
1508 return true;
1509 }
1510
1511 // Deal with other callbacks.
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001512 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event, code);
1513 // Errors are already logged if null
1514 if (info == null) return false;
Paul Hu83ec7f42023-06-07 18:04:09 +08001515 mServiceLogs.log(String.format(
1516 "MdnsDiscoveryManager event code=%s transactionId=%d",
1517 NsdManager.nameOf(code), transactionId));
Paul Hu019621e2023-01-13 23:26:49 +08001518 switch (code) {
1519 case NsdManager.SERVICE_FOUND:
Paul Hu812e9212023-06-20 06:24:53 +00001520 clientInfo.onServiceFound(clientRequestId, info, request);
Paul Hu319751a2023-01-13 23:56:34 +08001521 break;
1522 case NsdManager.SERVICE_LOST:
Paul Hu812e9212023-06-20 06:24:53 +00001523 clientInfo.onServiceLost(clientRequestId, info, request);
Paul Hu019621e2023-01-13 23:26:49 +08001524 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001525 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
1526 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Paul Hu75069ed2023-01-14 00:31:09 +08001527 info.setPort(serviceInfo.getPort());
1528
1529 Map<String, String> attrs = serviceInfo.getAttributes();
1530 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1531 final String key = kv.getKey();
1532 try {
1533 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1534 } catch (IllegalArgumentException e) {
1535 Log.e(TAG, "Invalid attribute", e);
1536 }
1537 }
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001538 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu2b865912023-03-06 14:27:53 +08001539 if (addresses.size() != 0) {
1540 info.setHostAddresses(addresses);
Paul Hua6bc4632023-06-26 01:18:29 +00001541 request.setServiceFromCache(event.mIsServiceFromCache);
1542 clientInfo.onResolveServiceSucceeded(clientRequestId, info, request);
Paul Hu2b865912023-03-06 14:27:53 +08001543 } else {
1544 // No address. Notify resolution failure.
Paul Hua6bc4632023-06-26 01:18:29 +00001545 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001546 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */,
1547 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001548 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu75069ed2023-01-14 00:31:09 +08001549 }
1550
1551 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001552 if (!(request instanceof DiscoveryManagerRequest)) {
1553 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1554 break;
1555 }
Paul Hud44e1b72023-06-16 02:07:42 +00001556 stopDiscoveryManagerRequest(
1557 request, clientRequestId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001558 break;
1559 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001560 case NsdManager.SERVICE_UPDATED: {
1561 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1562 info.setPort(serviceInfo.getPort());
1563
1564 Map<String, String> attrs = serviceInfo.getAttributes();
1565 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1566 final String key = kv.getKey();
1567 try {
1568 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1569 } catch (IllegalArgumentException e) {
1570 Log.e(TAG, "Invalid attribute", e);
1571 }
1572 }
1573
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001574 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001575 info.setHostAddresses(addresses);
Paul Huddce5912023-08-01 10:26:49 +08001576 clientInfo.onServiceUpdated(clientRequestId, info, request);
1577 // Set the ServiceFromCache flag only if the service is actually being
1578 // retrieved from the cache. This flag should not be overridden by later
1579 // service updates, which may not be cached.
1580 if (event.mIsServiceFromCache) {
1581 request.setServiceFromCache(true);
1582 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001583 break;
1584 }
1585 case NsdManager.SERVICE_UPDATED_LOST:
Paul Huddce5912023-08-01 10:26:49 +08001586 clientInfo.onServiceUpdatedLost(clientRequestId, request);
Paul Hu30bd70d2023-02-07 13:20:56 +00001587 break;
Paul Hu019621e2023-01-13 23:26:49 +08001588 default:
1589 return false;
1590 }
1591 return true;
1592 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001593 }
1594 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001595
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001596 @NonNull
1597 private static List<InetAddress> getInetAddresses(@NonNull MdnsServiceInfo serviceInfo) {
1598 final List<String> v4Addrs = serviceInfo.getIpv4Addresses();
1599 final List<String> v6Addrs = serviceInfo.getIpv6Addresses();
1600 final List<InetAddress> addresses = new ArrayList<>(v4Addrs.size() + v6Addrs.size());
1601 for (String ipv4Address : v4Addrs) {
1602 try {
1603 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1604 } catch (IllegalArgumentException e) {
1605 Log.wtf(TAG, "Invalid ipv4 address", e);
1606 }
1607 }
1608 for (String ipv6Address : v6Addrs) {
1609 try {
Yuyang Huanga6a6ff92023-04-24 13:33:34 +09001610 final Inet6Address addr = (Inet6Address) InetAddresses.parseNumericAddress(
1611 ipv6Address);
1612 addresses.add(InetAddressUtils.withScopeId(addr, serviceInfo.getInterfaceIndex()));
1613 } catch (IllegalArgumentException e) {
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001614 Log.wtf(TAG, "Invalid ipv6 address", e);
1615 }
1616 }
1617 return addresses;
1618 }
1619
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001620 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1621 switch (netId) {
1622 case NETID_UNSET:
1623 info.setNetwork(null);
1624 break;
1625 case INetd.LOCAL_NET_ID:
1626 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1627 // visible / usable for apps, so do not return it. Store the interface
1628 // index instead, so at least if the client tries to resolve the service
1629 // with that NsdServiceInfo, it will be done on the same interface.
1630 // If they recreate the NsdServiceInfo themselves, resolution would be
1631 // done on all interfaces as before T, which should also work.
1632 info.setNetwork(null);
1633 info.setInterfaceIndex(ifaceIdx);
1634 break;
1635 default:
1636 info.setNetwork(new Network(netId));
1637 }
1638 }
1639
paulhube186602022-04-12 07:18:23 +00001640 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1641 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1642 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1643 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1644 private String unescape(String s) {
1645 StringBuilder sb = new StringBuilder(s.length());
1646 for (int i = 0; i < s.length(); ++i) {
1647 char c = s.charAt(i);
1648 if (c == '\\') {
1649 if (++i >= s.length()) {
1650 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1651 break;
1652 }
1653 c = s.charAt(i);
1654 if (c != '.' && c != '\\') {
1655 if (i + 2 >= s.length()) {
1656 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1657 break;
1658 }
1659 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1660 + (s.charAt(i + 2) - '0'));
1661 i += 2;
1662 }
1663 }
1664 sb.append(c);
1665 }
1666 return sb.toString();
1667 }
1668
Paul Hu7445e3d2023-03-03 15:14:00 +08001669 /**
1670 * Check the given service type is valid and construct it to a service type
1671 * which can use for discovery / resolution service.
1672 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001673 * <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 +08001674 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1675 * underscore; they are alphanumerical characters or dashes or underscore, except the
1676 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1677 *
Yuyang Huang170d42f2023-12-09 15:26:16 +09001678 * <p>The subtypes may also be specified with a comma after the service type, for example
1679 * _type._tcp,_subtype1,_subtype2
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001680 *
Paul Hu7445e3d2023-03-03 15:14:00 +08001681 * @param serviceType the request service type for discovery / resolution service
1682 * @return constructed service type or null if the given service type is invalid.
1683 */
1684 @Nullable
Yuyang Huang170d42f2023-12-09 15:26:16 +09001685 public static Pair<String, List<String>> parseTypeAndSubtype(String serviceType) {
Paul Hu7445e3d2023-03-03 15:14:00 +08001686 if (TextUtils.isEmpty(serviceType)) return null;
Yuyang Huang86d083f2023-12-12 19:56:41 +09001687 final Pattern serviceTypePattern = Pattern.compile(TYPE_REGEX);
Paul Hu7445e3d2023-03-03 15:14:00 +08001688 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1689 if (!matcher.matches()) return null;
Yuyang Huang170d42f2023-12-09 15:26:16 +09001690 final String queryType = matcher.group(2);
1691 // Use the subtype at the beginning
1692 if (matcher.group(1) != null) {
1693 return new Pair<>(queryType, List.of(matcher.group(1)));
1694 }
1695 // Use the subtypes at the end
1696 final String subTypesStr = matcher.group(3);
1697 if (subTypesStr != null && !subTypesStr.isEmpty()) {
1698 final String[] subTypes = subTypesStr.substring(1).split(",");
1699 return new Pair<>(queryType, List.of(subTypes));
1700 }
1701
1702 return new Pair<>(queryType, Collections.emptyList());
Paul Hu7445e3d2023-03-03 15:14:00 +08001703 }
1704
Kangping Dong5af24b62023-12-10 21:41:16 +08001705 /** Returns {@code true} if {@code subtype} is a valid DNS-SD subtype label. */
1706 private static boolean checkSubtypeLabel(String subtype) {
1707 return Pattern.compile("^" + TYPE_SUBTYPE_LABEL_REGEX + "$").matcher(subtype).matches();
1708 }
1709
Hugo Benichi803a2f02017-04-24 11:35:06 +09001710 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001711 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001712 this(ctx, handler, cleanupDelayMs, new Dependencies());
1713 }
1714
1715 @VisibleForTesting
1716 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001717 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001718 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001719 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001720 mNsdStateMachine.start();
Ken Chen80c9f6f2023-11-15 18:24:54 +08001721 // It can fail on V+ device since mdns native service provided by netd is removed.
1722 mMDnsManager = SdkLevel.isAtLeastV() ? null : ctx.getSystemService(MDnsManager.class);
paulhu2b9ed952022-02-10 21:58:32 +08001723 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001724 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001725
Paul Hu14667de2023-04-17 22:42:47 +08001726 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper(),
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001727 LOGGER.forSubComponent("MdnsSocketProvider"), new SocketRequestMonitor());
Yuyang Huang700778b2023-03-08 16:17:05 +09001728 // Netlink monitor starts on boot, and intentionally never stopped, to ensure that all
Yuyang Huangfca402a2023-05-24 14:45:59 +09001729 // address events are received. When the netlink monitor starts, any IP addresses already
1730 // on the interfaces will not be seen. In practice, the network will not connect at boot
1731 // time As a result, all the netlink message should be observed if the netlink monitor
1732 // starts here.
Yuyang Huang700778b2023-03-08 16:17:05 +09001733 handler.post(mMdnsSocketProvider::startNetLinkMonitor);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001734
1735 // NsdService is started after ActivityManager (startOtherServices in SystemServer, vs.
1736 // startBootstrapServices).
1737 mRunningAppActiveImportanceCutoff = mDeps.getDeviceConfigInt(
1738 MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF,
1739 DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF);
1740 final ActivityManager am = ctx.getSystemService(ActivityManager.class);
1741 am.addOnUidImportanceListener(new UidImportanceListener(handler),
1742 mRunningAppActiveImportanceCutoff);
1743
Paul Huf3fe3332023-10-16 17:13:25 +08001744 final MdnsFeatureFlags flags = new MdnsFeatureFlags.Builder()
1745 .setIsMdnsOffloadFeatureEnabled(mDeps.isTetheringFeatureNotChickenedOut(
1746 mContext, MdnsFeatureFlags.NSD_FORCE_DISABLE_MDNS_OFFLOAD))
1747 .setIncludeInetAddressRecordsInProbing(mDeps.isFeatureEnabled(
1748 mContext, MdnsFeatureFlags.INCLUDE_INET_ADDRESS_RECORDS_IN_PROBING))
Paul Hu596a5002023-10-18 17:07:31 +08001749 .setIsExpiredServicesRemovalEnabled(mDeps.isFeatureEnabled(
1750 mContext, MdnsFeatureFlags.NSD_EXPIRED_SERVICES_REMOVAL))
Paul Hufd357ef2023-11-01 16:32:45 +08001751 .setIsLabelCountLimitEnabled(mDeps.isTetheringFeatureNotChickenedOut(
1752 mContext, MdnsFeatureFlags.NSD_LIMIT_LABEL_COUNT))
Paul Hu01f243f2023-11-22 17:26:36 +08001753 .setIsKnownAnswerSuppressionEnabled(mDeps.isFeatureEnabled(
1754 mContext, MdnsFeatureFlags.NSD_KNOWN_ANSWER_SUPPRESSION))
Remi NGUYEN VAN0ca094b2023-09-13 16:27:12 +09001755 .setIsUnicastReplyEnabled(mDeps.isFeatureEnabled(
1756 mContext, MdnsFeatureFlags.NSD_UNICAST_REPLY_ENABLED))
1757 .setOverrideProvider(flag -> mDeps.isFeatureEnabled(
1758 mContext, FORCE_ENABLE_FLAG_FOR_TEST_PREFIX + flag))
Paul Huf3fe3332023-10-16 17:13:25 +08001759 .build();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001760 mMdnsSocketClient =
Yuyang Huang7ddf2932023-08-01 18:16:30 +09001761 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider,
Paul Hufd357ef2023-11-01 16:32:45 +08001762 LOGGER.forSubComponent("MdnsMultinetworkSocketClient"), flags);
Paul Hu14667de2023-04-17 22:42:47 +08001763 mMdnsDiscoveryManager = deps.makeMdnsDiscoveryManager(new ExecutorProvider(),
Paul Huf3fe3332023-10-16 17:13:25 +08001764 mMdnsSocketClient, LOGGER.forSubComponent("MdnsDiscoveryManager"), flags);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001765 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1766 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
Remi NGUYEN VAN5c9d6cb2024-01-23 17:14:55 +09001767 new AdvertiserCallback(), LOGGER.forSubComponent("MdnsAdvertiser"), flags,
1768 mContext);
Paul Hu777ed052023-06-19 13:35:15 +00001769 mClock = deps.makeClock();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001770 }
1771
1772 /**
1773 * Dependencies of NsdService, for injection in tests.
1774 */
1775 @VisibleForTesting
1776 public static class Dependencies {
1777 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001778 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001779 *
1780 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001781 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001782 */
1783 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001784 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001785 MDNS_DISCOVERY_MANAGER_VERSION);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001786 }
1787
1788 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001789 * Check whether the MdnsAdvertiser feature is enabled.
1790 *
1791 * @param context The global context information about an app environment.
1792 * @return true if the MdnsAdvertiser feature is enabled.
1793 */
1794 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001795 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001796 MDNS_ADVERTISER_VERSION);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001797 }
1798
1799 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001800 * Get the type allowlist flag value.
1801 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1802 */
1803 @Nullable
1804 public String getTypeAllowlistFlags() {
1805 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1806 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1807 }
1808
1809 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001810 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001811 */
1812 public boolean isFeatureEnabled(Context context, String feature) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001813 return DeviceConfigUtils.isTetheringFeatureEnabled(context, feature);
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001814 }
1815
1816 /**
Yuyang Huangb96a0712023-09-07 15:13:15 +09001817 * @see DeviceConfigUtils#isTetheringFeatureNotChickenedOut
1818 */
Motomu Utsumied4e7ec2023-09-13 14:58:32 +09001819 public boolean isTetheringFeatureNotChickenedOut(Context context, String feature) {
1820 return DeviceConfigUtils.isTetheringFeatureNotChickenedOut(context, feature);
Yuyang Huangb96a0712023-09-07 15:13:15 +09001821 }
1822
1823 /**
Paul Huf3fe3332023-10-16 17:13:25 +08001824 * @see DeviceConfigUtils#isTrunkStableFeatureEnabled
1825 */
1826 public boolean isTrunkStableFeatureEnabled(String feature) {
1827 return DeviceConfigUtils.isTrunkStableFeatureEnabled(feature);
1828 }
1829
1830 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001831 * @see MdnsDiscoveryManager
1832 */
1833 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
Paul Hu14667de2023-04-17 22:42:47 +08001834 @NonNull ExecutorProvider executorProvider,
Paul Huf3fe3332023-10-16 17:13:25 +08001835 @NonNull MdnsMultinetworkSocketClient socketClient, @NonNull SharedLog sharedLog,
1836 @NonNull MdnsFeatureFlags featureFlags) {
1837 return new MdnsDiscoveryManager(
1838 executorProvider, socketClient, sharedLog, featureFlags);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001839 }
1840
1841 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001842 * @see MdnsAdvertiser
1843 */
1844 public MdnsAdvertiser makeMdnsAdvertiser(
1845 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
Yuyang Huangb96a0712023-09-07 15:13:15 +09001846 @NonNull MdnsAdvertiser.AdvertiserCallback cb, @NonNull SharedLog sharedLog,
Remi NGUYEN VAN5c9d6cb2024-01-23 17:14:55 +09001847 MdnsFeatureFlags featureFlags, Context context) {
1848 return new MdnsAdvertiser(looper, socketProvider, cb, sharedLog, featureFlags, context);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001849 }
1850
1851 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001852 * @see MdnsSocketProvider
1853 */
Paul Hu14667de2023-04-17 22:42:47 +08001854 public MdnsSocketProvider makeMdnsSocketProvider(@NonNull Context context,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001855 @NonNull Looper looper, @NonNull SharedLog sharedLog,
1856 @NonNull MdnsSocketProvider.SocketRequestMonitor socketCreationCallback) {
1857 return new MdnsSocketProvider(context, looper, sharedLog, socketCreationCallback);
1858 }
1859
1860 /**
1861 * @see DeviceConfig#getInt(String, String, int)
1862 */
1863 public int getDeviceConfigInt(@NonNull String config, int defaultValue) {
1864 return DeviceConfig.getInt(NAMESPACE_TETHERING, config, defaultValue);
1865 }
1866
1867 /**
1868 * @see Binder#getCallingUid()
1869 */
1870 public int getCallingUid() {
1871 return Binder.getCallingUid();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001872 }
Paul Hu777ed052023-06-19 13:35:15 +00001873
1874 /**
1875 * @see NetworkNsdReportedMetrics
1876 */
Paul Hu508a0122023-09-11 15:31:33 +08001877 public NetworkNsdReportedMetrics makeNetworkNsdReportedMetrics(int clientId) {
1878 return new NetworkNsdReportedMetrics(clientId);
Paul Hu777ed052023-06-19 13:35:15 +00001879 }
1880
1881 /**
1882 * @see MdnsUtils.Clock
1883 */
1884 public Clock makeClock() {
1885 return new Clock();
1886 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001887 }
1888
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001889 /**
1890 * Return whether a type is allowlisted to use the Java backend.
1891 * @param type The service type
1892 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1893 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1894 */
1895 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1896 @NonNull String flagPrefix) {
1897 if (type == null) return false;
1898 final String typesConfig = mDeps.getTypeAllowlistFlags();
1899 if (TextUtils.isEmpty(typesConfig)) return false;
1900
1901 final String mappingPrefix = type + ":";
1902 String mappedFlag = null;
1903 for (String mapping : TextUtils.split(typesConfig, ",")) {
1904 if (mapping.startsWith(mappingPrefix)) {
1905 mappedFlag = mapping.substring(mappingPrefix.length());
1906 break;
1907 }
1908 }
1909
1910 if (mappedFlag == null) return false;
1911
1912 return mDeps.isFeatureEnabled(mContext,
1913 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1914 }
1915
1916 private boolean useDiscoveryManagerForType(@Nullable String type) {
1917 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1918 }
1919
1920 private boolean useAdvertiserForType(@Nullable String type) {
1921 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1922 }
1923
paulhu1b35e822022-04-08 14:48:41 +08001924 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001925 HandlerThread thread = new HandlerThread(TAG);
1926 thread.start();
1927 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001928 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001929 return service;
1930 }
1931
paulhu2b9ed952022-02-10 21:58:32 +08001932 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1933 private final StateMachine mStateMachine;
1934
1935 MDnsEventCallback(StateMachine sm) {
1936 mStateMachine = sm;
1937 }
1938
1939 @Override
1940 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1941 mStateMachine.sendMessage(
1942 MDNS_SERVICE_EVENT, status.result, status.id, status);
1943 }
1944
1945 @Override
1946 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1947 mStateMachine.sendMessage(
1948 MDNS_SERVICE_EVENT, status.result, status.id, status);
1949 }
1950
1951 @Override
1952 public void onServiceResolutionStatus(final ResolutionInfo status) {
1953 mStateMachine.sendMessage(
1954 MDNS_SERVICE_EVENT, status.result, status.id, status);
1955 }
1956
1957 @Override
1958 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1959 mStateMachine.sendMessage(
1960 MDNS_SERVICE_EVENT, status.result, status.id, status);
1961 }
1962
1963 @Override
1964 public int getInterfaceVersion() throws RemoteException {
1965 return this.VERSION;
1966 }
1967
1968 @Override
1969 public String getInterfaceHash() throws RemoteException {
1970 return this.HASH;
1971 }
1972 }
1973
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001974 private void sendAllOffloadServiceInfos(@NonNull OffloadEngineInfo offloadEngineInfo) {
1975 final String targetInterface = offloadEngineInfo.mInterfaceName;
1976 final IOffloadEngine offloadEngine = offloadEngineInfo.mOffloadEngine;
1977 final List<MdnsAdvertiser.OffloadServiceInfoWrapper> offloadWrappers =
1978 mAdvertiser.getAllInterfaceOffloadServiceInfos(targetInterface);
1979 for (MdnsAdvertiser.OffloadServiceInfoWrapper wrapper : offloadWrappers) {
1980 try {
1981 offloadEngine.onOffloadServiceUpdated(wrapper.mOffloadServiceInfo);
1982 } catch (RemoteException e) {
1983 // Can happen in regular cases, do not log a stacktrace
1984 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
1985 }
1986 }
1987 }
1988
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001989 private void sendOffloadServiceInfosUpdate(@NonNull String targetInterfaceName,
1990 @NonNull OffloadServiceInfo offloadServiceInfo, boolean isRemove) {
1991 final int count = mOffloadEngines.beginBroadcast();
1992 try {
1993 for (int i = 0; i < count; i++) {
1994 final OffloadEngineInfo offloadEngineInfo =
1995 (OffloadEngineInfo) mOffloadEngines.getBroadcastCookie(i);
1996 final String interfaceName = offloadEngineInfo.mInterfaceName;
1997 if (!targetInterfaceName.equals(interfaceName)
1998 || ((offloadEngineInfo.mOffloadType
1999 & offloadServiceInfo.getOffloadType()) == 0)) {
2000 continue;
2001 }
2002 try {
2003 if (isRemove) {
2004 mOffloadEngines.getBroadcastItem(i).onOffloadServiceRemoved(
2005 offloadServiceInfo);
2006 } else {
2007 mOffloadEngines.getBroadcastItem(i).onOffloadServiceUpdated(
2008 offloadServiceInfo);
2009 }
2010 } catch (RemoteException e) {
2011 // Can happen in regular cases, do not log a stacktrace
Yuyang Huangc275a9e2023-08-25 18:03:22 +09002012 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002013 }
2014 }
2015 } finally {
2016 mOffloadEngines.finishBroadcast();
2017 }
2018 }
2019
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002020 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002021 // TODO: add a callback to notify when a service is being added on each interface (as soon
2022 // as probing starts), and call mOffloadCallbacks. This callback is for
2023 // OFFLOAD_CAPABILITY_FILTER_REPLIES offload type.
2024
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002025 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00002026 public void onRegisterServiceSucceeded(int transactionId, NsdServiceInfo registeredInfo) {
2027 mServiceLogs.log("onRegisterServiceSucceeded: transactionId " + transactionId);
2028 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002029 if (clientInfo == null) return;
2030
Paul Hud44e1b72023-06-16 02:07:42 +00002031 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
2032 if (clientRequestId < 0) return;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002033
2034 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
2035 // historical behavior.
2036 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
Paul Hu777ed052023-06-19 13:35:15 +00002037 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu508a0122023-09-11 15:31:33 +08002038 clientInfo.onRegisterServiceSucceeded(clientRequestId, cbInfo, request);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002039 }
2040
2041 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00002042 public void onRegisterServiceFailed(int transactionId, int errorCode) {
2043 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002044 if (clientInfo == null) return;
2045
Paul Hud44e1b72023-06-16 02:07:42 +00002046 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
2047 if (clientRequestId < 0) return;
Paul Hu777ed052023-06-19 13:35:15 +00002048 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu508a0122023-09-11 15:31:33 +08002049 clientInfo.onRegisterServiceFailed(clientRequestId, errorCode, false /* isLegacy */,
2050 transactionId, request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002051 }
2052
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002053 @Override
2054 public void onOffloadStartOrUpdate(@NonNull String interfaceName,
2055 @NonNull OffloadServiceInfo offloadServiceInfo) {
2056 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, false /* isRemove */);
2057 }
2058
2059 @Override
2060 public void onOffloadStop(@NonNull String interfaceName,
2061 @NonNull OffloadServiceInfo offloadServiceInfo) {
2062 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, true /* isRemove */);
2063 }
2064
Paul Hud44e1b72023-06-16 02:07:42 +00002065 private ClientInfo getClientInfoOrLog(int transactionId) {
2066 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002067 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00002068 Log.e(TAG, String.format("Callback for service %d has no client", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002069 }
2070 return clientInfo;
2071 }
2072
Paul Hud44e1b72023-06-16 02:07:42 +00002073 private int getClientRequestIdOrLog(@NonNull ClientInfo info, int transactionId) {
2074 final int clientRequestId = info.getClientRequestId(transactionId);
2075 if (clientRequestId < 0) {
2076 Log.e(TAG, String.format(
2077 "Client request ID not found for service %d", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002078 }
Paul Hud44e1b72023-06-16 02:07:42 +00002079 return clientRequestId;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002080 }
2081 }
2082
Paul Hu2e0a88c2023-03-09 16:05:01 +08002083 private static class ConnectorArgs {
2084 @NonNull public final NsdServiceConnector connector;
2085 @NonNull public final INsdManagerCallback callback;
2086 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002087 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002088
2089 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00002090 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08002091 this.connector = connector;
2092 this.callback = callback;
2093 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002094 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002095 }
2096 }
2097
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002098 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08002099 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09002100 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu101dbf52023-08-09 16:05:20 +08002101 final int uid = mDeps.getCallingUid();
2102 if (cb == null) {
2103 throw new IllegalArgumentException("Unknown client callback from uid=" + uid);
2104 }
Paul Hu2e0a88c2023-03-09 16:05:01 +08002105 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002106 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00002107 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
Paul Hu101dbf52023-08-09 16:05:20 +08002108 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend, uid)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002109 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07002110 }
2111
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002112 private static class ListenerArgs {
2113 public final NsdServiceConnector connector;
2114 public final NsdServiceInfo serviceInfo;
2115 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
2116 this.connector = connector;
2117 this.serviceInfo = serviceInfo;
2118 }
2119 }
2120
Yuyang Huang86d083f2023-12-12 19:56:41 +09002121 private static class AdvertisingArgs {
2122 public final NsdServiceConnector connector;
2123 public final AdvertisingRequest advertisingRequest;
2124
2125 AdvertisingArgs(NsdServiceConnector connector, AdvertisingRequest advertisingRequest) {
2126 this.connector = connector;
2127 this.advertisingRequest = advertisingRequest;
2128 }
2129 }
2130
Kangping Dong1f1a3792023-12-10 22:05:04 +08002131 private static final class DiscoveryArgs {
2132 public final NsdServiceConnector connector;
2133 public final DiscoveryRequest discoveryRequest;
2134 DiscoveryArgs(NsdServiceConnector connector, DiscoveryRequest discoveryRequest) {
2135 this.connector = connector;
2136 this.discoveryRequest = discoveryRequest;
2137 }
2138 }
2139
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002140 private class NsdServiceConnector extends INsdServiceConnector.Stub
2141 implements IBinder.DeathRecipient {
Yuyang Huang86d083f2023-12-12 19:56:41 +09002142
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002143 @Override
Yuyang Huang86d083f2023-12-12 19:56:41 +09002144 public void registerService(int listenerKey, AdvertisingRequest advertisingRequest)
2145 throws RemoteException {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002146 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2147 NsdManager.REGISTER_SERVICE, 0, listenerKey,
Yuyang Huang86d083f2023-12-12 19:56:41 +09002148 new AdvertisingArgs(this, advertisingRequest)
2149 ));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002150 }
2151
2152 @Override
2153 public void unregisterService(int listenerKey) {
2154 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2155 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
Yuyang Huang86d083f2023-12-12 19:56:41 +09002156 new ListenerArgs(this, (NsdServiceInfo) null)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002157 }
2158
2159 @Override
Kangping Dong1f1a3792023-12-10 22:05:04 +08002160 public void discoverServices(int listenerKey, DiscoveryRequest discoveryRequest) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002161 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2162 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
Kangping Dong1f1a3792023-12-10 22:05:04 +08002163 new DiscoveryArgs(this, discoveryRequest)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002164 }
2165
2166 @Override
2167 public void stopDiscovery(int listenerKey) {
Yuyang Huang86d083f2023-12-12 19:56:41 +09002168 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.STOP_DISCOVERY,
2169 0, listenerKey, new ListenerArgs(this, (NsdServiceInfo) null)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002170 }
2171
2172 @Override
2173 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
2174 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2175 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
2176 new ListenerArgs(this, serviceInfo)));
2177 }
2178
2179 @Override
Paul Hub58deb72022-12-26 09:24:42 +00002180 public void stopResolution(int listenerKey) {
Yuyang Huang86d083f2023-12-12 19:56:41 +09002181 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.STOP_RESOLUTION,
2182 0, listenerKey, new ListenerArgs(this, (NsdServiceInfo) null)));
Paul Hub58deb72022-12-26 09:24:42 +00002183 }
2184
2185 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00002186 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
2187 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2188 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
2189 new ListenerArgs(this, serviceInfo)));
2190 }
2191
2192 @Override
2193 public void unregisterServiceInfoCallback(int listenerKey) {
2194 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2195 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
Yuyang Huang86d083f2023-12-12 19:56:41 +09002196 new ListenerArgs(this, (NsdServiceInfo) null)));
Paul Hu18aeccc2022-12-27 08:48:48 +00002197 }
2198
2199 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002200 public void startDaemon() {
Yuyang Huang86d083f2023-12-12 19:56:41 +09002201 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.DAEMON_STARTUP,
2202 new ListenerArgs(this, (NsdServiceInfo) null)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002203 }
2204
2205 @Override
2206 public void binderDied() {
2207 mNsdStateMachine.sendMessage(
2208 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002209
2210 }
2211
2212 @Override
2213 public void registerOffloadEngine(String ifaceName, IOffloadEngine cb,
2214 @OffloadEngine.OffloadCapability long offloadCapabilities,
2215 @OffloadEngine.OffloadType long offloadTypes) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002216 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002217 Objects.requireNonNull(ifaceName);
2218 Objects.requireNonNull(cb);
2219 mNsdStateMachine.sendMessage(
2220 mNsdStateMachine.obtainMessage(NsdManager.REGISTER_OFFLOAD_ENGINE,
2221 new OffloadEngineInfo(cb, ifaceName, offloadCapabilities,
2222 offloadTypes)));
2223 }
2224
2225 @Override
2226 public void unregisterOffloadEngine(IOffloadEngine cb) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002227 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002228 Objects.requireNonNull(cb);
2229 mNsdStateMachine.sendMessage(
2230 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_OFFLOAD_ENGINE, cb));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002231 }
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002232
2233 private static void checkOffloadEnginePermission(Context context) {
2234 if (!SdkLevel.isAtLeastT()) {
2235 throw new SecurityException("API is not available in before API level 33");
2236 }
Yuyang Huangd5896e72023-11-28 13:23:59 +09002237
Ken Chena7bae552023-12-27 11:40:57 +08002238 final ArrayList<String> permissionsList = new ArrayList<>(Arrays.asList(NETWORK_STACK,
2239 PERMISSION_MAINLINE_NETWORK_STACK, NETWORK_SETTINGS));
2240
2241 if (SdkLevel.isAtLeastV()) {
2242 // REGISTER_NSD_OFFLOAD_ENGINE was only added to the SDK in V.
2243 permissionsList.add(REGISTER_NSD_OFFLOAD_ENGINE);
2244 } else if (SdkLevel.isAtLeastU()) {
2245 // REGISTER_NSD_OFFLOAD_ENGINE cannot be backport to U. In U, check the DEVICE_POWER
2246 // permission instead.
2247 permissionsList.add(DEVICE_POWER);
Yuyang Huangd5896e72023-11-28 13:23:59 +09002248 }
2249
Ken Chena7bae552023-12-27 11:40:57 +08002250 if (PermissionUtils.checkAnyPermissionOf(context,
2251 permissionsList.toArray(new String[0]))) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002252 return;
2253 }
2254 throw new SecurityException("Requires one of the following permissions: "
Ken Chena7bae552023-12-27 11:40:57 +08002255 + String.join(", ", permissionsList) + ".");
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002256 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002257 }
2258
Hugo Benichi912db992017-04-24 16:41:03 +09002259 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07002260 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07002261 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09002262 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
2263 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07002264 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07002265 }
2266
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002267 private int getUniqueId() {
2268 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
2269 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002270 }
2271
Paul Hud44e1b72023-06-16 02:07:42 +00002272 private boolean registerService(int transactionId, NsdServiceInfo service) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002273 if (mMDnsManager == null) {
2274 Log.wtf(TAG, "registerService: mMDnsManager is null");
2275 return false;
2276 }
2277
Hugo Benichi6d706442017-04-24 16:19:58 +09002278 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002279 Log.d(TAG, "registerService: " + transactionId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002280 }
Hugo Benichi6d706442017-04-24 16:19:58 +09002281 String name = service.getServiceName();
2282 String type = service.getServiceType();
2283 int port = service.getPort();
2284 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002285 final int registerInterface = getNetworkInterfaceIndex(service);
2286 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08002287 Log.e(TAG, "Interface to register service on not found");
2288 return false;
2289 }
Paul Hud44e1b72023-06-16 02:07:42 +00002290 return mMDnsManager.registerService(
2291 transactionId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002292 }
2293
Paul Hud44e1b72023-06-16 02:07:42 +00002294 private boolean unregisterService(int transactionId) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002295 if (mMDnsManager == null) {
2296 Log.wtf(TAG, "unregisterService: mMDnsManager is null");
2297 return false;
2298 }
Paul Hud44e1b72023-06-16 02:07:42 +00002299 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002300 }
2301
Kangping Dong1f1a3792023-12-10 22:05:04 +08002302 private boolean discoverServices(int transactionId, DiscoveryRequest discoveryRequest) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002303 if (mMDnsManager == null) {
2304 Log.wtf(TAG, "discoverServices: mMDnsManager is null");
2305 return false;
2306 }
2307
Kangping Dong1f1a3792023-12-10 22:05:04 +08002308 final String type = discoveryRequest.getServiceType();
2309 final int discoverInterface = getNetworkInterfaceIndex(discoveryRequest);
2310 if (discoveryRequest.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002311 Log.e(TAG, "Interface to discover service on not found");
2312 return false;
2313 }
Paul Hud44e1b72023-06-16 02:07:42 +00002314 return mMDnsManager.discover(transactionId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002315 }
2316
Paul Hud44e1b72023-06-16 02:07:42 +00002317 private boolean stopServiceDiscovery(int transactionId) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002318 if (mMDnsManager == null) {
2319 Log.wtf(TAG, "stopServiceDiscovery: mMDnsManager is null");
2320 return false;
2321 }
Paul Hud44e1b72023-06-16 02:07:42 +00002322 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002323 }
2324
Paul Hud44e1b72023-06-16 02:07:42 +00002325 private boolean resolveService(int transactionId, NsdServiceInfo service) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002326 if (mMDnsManager == null) {
2327 Log.wtf(TAG, "resolveService: mMDnsManager is null");
2328 return false;
2329 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002330 final String name = service.getServiceName();
2331 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002332 final int resolveInterface = getNetworkInterfaceIndex(service);
2333 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002334 Log.e(TAG, "Interface to resolve service on not found");
2335 return false;
2336 }
Paul Hud44e1b72023-06-16 02:07:42 +00002337 return mMDnsManager.resolve(transactionId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002338 }
2339
2340 /**
2341 * Guess the interface to use to resolve or discover a service on a specific network.
2342 *
2343 * This is an imperfect guess, as for example the network may be gone or not yet fully
2344 * registered. This is fine as failing is correct if the network is gone, and a client
2345 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
2346 * this is to support the legacy mdnsresponder implementation, which historically resolved
2347 * services on an unspecified network.
2348 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002349 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
2350 final Network network = serviceInfo.getNetwork();
2351 if (network == null) {
2352 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
2353 // provided by NsdService from discovery results, and the service was found on an
2354 // interface that has no app-usable Network).
2355 if (serviceInfo.getInterfaceIndex() != 0) {
2356 return serviceInfo.getInterfaceIndex();
2357 }
2358 return IFACE_IDX_ANY;
2359 }
Kangping Dong1f1a3792023-12-10 22:05:04 +08002360 return getNetworkInterfaceIndex(network);
2361 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002362
Kangping Dong1f1a3792023-12-10 22:05:04 +08002363 /**
2364 * Returns the interface to use to discover a service on a specific network, or {@link
2365 * IFACE_IDX_ANY} if no network is specified.
2366 */
2367 private int getNetworkInterfaceIndex(DiscoveryRequest discoveryRequest) {
2368 final Network network = discoveryRequest.getNetwork();
2369 if (network == null) {
2370 return IFACE_IDX_ANY;
2371 }
2372 return getNetworkInterfaceIndex(network);
2373 }
2374
2375 /**
2376 * Returns the interface of a specific network, or {@link IFACE_IDX_ANY} if no interface is
2377 * associated with {@code network}.
2378 */
2379 private int getNetworkInterfaceIndex(@NonNull Network network) {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002380 String interfaceName = getNetworkInterfaceName(network);
2381 if (interfaceName == null) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002382 return IFACE_IDX_ANY;
2383 }
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002384 return getNetworkInterfaceIndexByName(interfaceName);
2385 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002386
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002387 private String getNetworkInterfaceName(@Nullable Network network) {
2388 if (network == null) {
2389 return null;
2390 }
2391 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
2392 if (cm == null) {
2393 Log.wtf(TAG, "No ConnectivityManager");
2394 return null;
2395 }
2396 final LinkProperties lp = cm.getLinkProperties(network);
2397 if (lp == null) {
2398 return null;
2399 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002400 // Only resolve on non-stacked interfaces
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002401 return lp.getInterfaceName();
2402 }
2403
2404 private int getNetworkInterfaceIndexByName(final String ifaceName) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002405 final NetworkInterface iface;
2406 try {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002407 iface = NetworkInterface.getByName(ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002408 } catch (SocketException e) {
2409 Log.e(TAG, "Error querying interface", e);
2410 return IFACE_IDX_ANY;
2411 }
2412
2413 if (iface == null) {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002414 Log.e(TAG, "Interface not found: " + ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002415 return IFACE_IDX_ANY;
2416 }
2417
2418 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002419 }
2420
Paul Hud44e1b72023-06-16 02:07:42 +00002421 private boolean stopResolveService(int transactionId) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002422 if (mMDnsManager == null) {
2423 Log.wtf(TAG, "stopResolveService: mMDnsManager is null");
2424 return false;
2425 }
Paul Hud44e1b72023-06-16 02:07:42 +00002426 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002427 }
2428
Paul Hud44e1b72023-06-16 02:07:42 +00002429 private boolean getAddrInfo(int transactionId, String hostname, int interfaceIdx) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002430 if (mMDnsManager == null) {
2431 Log.wtf(TAG, "getAddrInfo: mMDnsManager is null");
2432 return false;
2433 }
Paul Hud44e1b72023-06-16 02:07:42 +00002434 return mMDnsManager.getServiceAddress(transactionId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002435 }
2436
Paul Hud44e1b72023-06-16 02:07:42 +00002437 private boolean stopGetAddrInfo(int transactionId) {
Ken Chen80c9f6f2023-11-15 18:24:54 +08002438 if (mMDnsManager == null) {
2439 Log.wtf(TAG, "stopGetAddrInfo: mMDnsManager is null");
2440 return false;
2441 }
Paul Hud44e1b72023-06-16 02:07:42 +00002442 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002443 }
2444
2445 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00002446 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2447 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002448
Paul Hub2e67d32023-04-18 05:50:14 +00002449 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2450 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07002451 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00002452
2453 // Dump service and clients logs
2454 pw.println();
Paul Hu14667de2023-04-17 22:42:47 +08002455 pw.println("Logs:");
Paul Hub2e67d32023-04-18 05:50:14 +00002456 pw.increaseIndent();
2457 mServiceLogs.reverseDump(pw);
2458 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002459 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002460
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002461 private abstract static class ClientRequest {
Paul Hud44e1b72023-06-16 02:07:42 +00002462 private final int mTransactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002463 private final long mStartTimeMs;
Paul Hu812e9212023-06-20 06:24:53 +00002464 private int mFoundServiceCount = 0;
2465 private int mLostServiceCount = 0;
2466 private final Set<String> mServices = new ArraySet<>();
Paul Hua6bc4632023-06-26 01:18:29 +00002467 private boolean mIsServiceFromCache = false;
Paul Hubad6fe92023-07-24 21:25:22 +08002468 private int mSentQueryCount = NO_SENT_QUERY_COUNT;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002469
Paul Hu812e9212023-06-20 06:24:53 +00002470 private ClientRequest(int transactionId, long startTimeMs) {
Paul Hud44e1b72023-06-16 02:07:42 +00002471 mTransactionId = transactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002472 mStartTimeMs = startTimeMs;
2473 }
2474
Paul Hu812e9212023-06-20 06:24:53 +00002475 public long calculateRequestDurationMs(long stopTimeMs) {
Paul Hu777ed052023-06-19 13:35:15 +00002476 return stopTimeMs - mStartTimeMs;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002477 }
Paul Hu812e9212023-06-20 06:24:53 +00002478
2479 public void onServiceFound(String serviceName) {
2480 mFoundServiceCount++;
2481 if (mServices.size() <= MAX_SERVICES_COUNT_METRIC_PER_CLIENT) {
2482 mServices.add(serviceName);
2483 }
2484 }
2485
2486 public void onServiceLost() {
2487 mLostServiceCount++;
2488 }
2489
2490 public int getFoundServiceCount() {
2491 return mFoundServiceCount;
2492 }
2493
2494 public int getLostServiceCount() {
2495 return mLostServiceCount;
2496 }
2497
2498 public int getServicesCount() {
2499 return mServices.size();
2500 }
Paul Hua6bc4632023-06-26 01:18:29 +00002501
2502 public void setServiceFromCache(boolean isServiceFromCache) {
2503 mIsServiceFromCache = isServiceFromCache;
2504 }
2505
2506 public boolean isServiceFromCache() {
2507 return mIsServiceFromCache;
2508 }
Paul Hubad6fe92023-07-24 21:25:22 +08002509
2510 public void onQuerySent() {
2511 mSentQueryCount++;
2512 }
2513
2514 public int getSentQueryCount() {
2515 return mSentQueryCount;
2516 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002517 }
2518
2519 private static class LegacyClientRequest extends ClientRequest {
2520 private final int mRequestCode;
2521
Paul Hu812e9212023-06-20 06:24:53 +00002522 private LegacyClientRequest(int transactionId, int requestCode, long startTimeMs) {
2523 super(transactionId, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002524 mRequestCode = requestCode;
2525 }
2526 }
2527
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002528 private abstract static class JavaBackendClientRequest extends ClientRequest {
2529 @Nullable
2530 private final Network mRequestedNetwork;
2531
Paul Hu777ed052023-06-19 13:35:15 +00002532 private JavaBackendClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002533 long startTimeMs) {
2534 super(transactionId, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002535 mRequestedNetwork = requestedNetwork;
2536 }
2537
2538 @Nullable
2539 public Network getRequestedNetwork() {
2540 return mRequestedNetwork;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002541 }
2542 }
2543
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002544 private static class AdvertiserClientRequest extends JavaBackendClientRequest {
Paul Hu777ed052023-06-19 13:35:15 +00002545 private AdvertiserClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002546 long startTimeMs) {
2547 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002548 }
2549 }
2550
2551 private static class DiscoveryManagerRequest extends JavaBackendClientRequest {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002552 @NonNull
2553 private final MdnsListener mListener;
2554
Paul Hud44e1b72023-06-16 02:07:42 +00002555 private DiscoveryManagerRequest(int transactionId, @NonNull MdnsListener listener,
Paul Hu812e9212023-06-20 06:24:53 +00002556 @Nullable Network requestedNetwork, long startTimeMs) {
2557 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002558 mListener = listener;
2559 }
2560 }
2561
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002562 /* Information tracked per client */
2563 private class ClientInfo {
2564
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002565 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002566 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002567 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002568 private NsdServiceInfo mResolvedService;
2569
Paul Hud44e1b72023-06-16 02:07:42 +00002570 /* A map from client request ID (listenerKey) to the request */
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002571 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08002572
Luke Huangf7277ed2021-07-12 21:15:10 +08002573 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002574 private boolean mIsPreSClient = false;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002575 private final int mUid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002576 // The flag of using java backend if the client's target SDK >= U
2577 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002578 // Store client logs
2579 private final SharedLog mClientLogs;
Paul Hucdef3532023-06-18 14:47:35 +00002580 // Report the nsd metrics data
2581 private final NetworkNsdReportedMetrics mMetrics;
Luke Huangf7277ed2021-07-12 21:15:10 +08002582
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002583 private ClientInfo(INsdManagerCallback cb, int uid, boolean useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +00002584 SharedLog sharedLog, NetworkNsdReportedMetrics metrics) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002585 mCb = cb;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002586 mUid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002587 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002588 mClientLogs = sharedLog;
2589 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Paul Hucdef3532023-06-18 14:47:35 +00002590 mMetrics = metrics;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002591 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002592
2593 @Override
2594 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06002595 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07002596 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002597 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002598 sb.append("mUseJavaBackend ").append(mUseJavaBackend).append("\n");
2599 sb.append("mUid ").append(mUid).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002600 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002601 int clientRequestId = mClientRequests.keyAt(i);
2602 sb.append("clientRequestId ")
2603 .append(clientRequestId)
2604 .append(" transactionId ").append(mClientRequests.valueAt(i).mTransactionId)
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002605 .append(" type ").append(
2606 mClientRequests.valueAt(i).getClass().getSimpleName())
2607 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07002608 }
2609 return sb.toString();
2610 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002611
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002612 private boolean isPreSClient() {
2613 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08002614 }
2615
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002616 private void setPreSClient() {
2617 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08002618 }
2619
Paul Hu812e9212023-06-20 06:24:53 +00002620 private MdnsListener unregisterMdnsListenerFromRequest(ClientRequest request) {
Paul Hue4f5f252023-02-16 21:13:47 +08002621 final MdnsListener listener =
2622 ((DiscoveryManagerRequest) request).mListener;
2623 mMdnsDiscoveryManager.unregisterListener(
2624 listener.getListenedServiceType(), listener);
Paul Hu812e9212023-06-20 06:24:53 +00002625 return listener;
Paul Hue4f5f252023-02-16 21:13:47 +08002626 }
2627
Dave Plattfeff2af2014-03-07 14:48:22 -08002628 // Remove any pending requests from the global map when we get rid of a client,
2629 // and send cancellations to the daemon.
2630 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00002631 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09002632 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002633 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002634 final int clientRequestId = mClientRequests.keyAt(i);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002635 final ClientRequest request = mClientRequests.valueAt(i);
Paul Hud44e1b72023-06-16 02:07:42 +00002636 final int transactionId = request.mTransactionId;
2637 mTransactionIdToClientInfoMap.remove(transactionId);
paulhub2225702021-11-17 09:35:33 +08002638 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002639 Log.d(TAG, "Terminating clientRequestId " + clientRequestId
2640 + " transactionId " + transactionId
2641 + " type " + mClientRequests.get(clientRequestId));
paulhub2225702021-11-17 09:35:33 +08002642 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002643
2644 if (request instanceof DiscoveryManagerRequest) {
Paul Hu812e9212023-06-20 06:24:53 +00002645 final MdnsListener listener = unregisterMdnsListenerFromRequest(request);
2646 if (listener instanceof DiscoveryListener) {
Paul Hu508a0122023-09-11 15:31:33 +08002647 mMetrics.reportServiceDiscoveryStop(false /* isLegacy */, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00002648 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2649 request.getFoundServiceCount(),
2650 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002651 request.getServicesCount(),
2652 request.getSentQueryCount());
Paul Hu60149052023-07-31 14:26:08 +08002653 } else if (listener instanceof ResolutionListener) {
Paul Hu508a0122023-09-11 15:31:33 +08002654 mMetrics.reportServiceResolutionStop(false /* isLegacy */, transactionId,
Paul Hu60149052023-07-31 14:26:08 +08002655 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Huddce5912023-08-01 10:26:49 +08002656 } else if (listener instanceof ServiceInfoListener) {
2657 mMetrics.reportServiceInfoCallbackUnregistered(transactionId,
2658 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2659 request.getFoundServiceCount(),
2660 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002661 request.isServiceFromCache(),
2662 request.getSentQueryCount());
Paul Hu812e9212023-06-20 06:24:53 +00002663 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002664 continue;
2665 }
2666
2667 if (request instanceof AdvertiserClientRequest) {
Paul Hu043bcd42023-07-14 16:38:25 +08002668 final AdvertiserMetrics metrics =
2669 mAdvertiser.getAdvertiserMetrics(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00002670 mAdvertiser.removeService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002671 mMetrics.reportServiceUnregistration(false /* isLegacy */, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002672 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2673 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2674 metrics.mConflictDuringProbingCount,
2675 metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002676 continue;
2677 }
2678
2679 if (!(request instanceof LegacyClientRequest)) {
2680 throw new IllegalStateException("Unknown request type: " + request.getClass());
2681 }
2682
2683 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08002684 case NsdManager.DISCOVER_SERVICES:
Paul Hud44e1b72023-06-16 02:07:42 +00002685 stopServiceDiscovery(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002686 mMetrics.reportServiceDiscoveryStop(true /* isLegacy */, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00002687 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2688 request.getFoundServiceCount(),
2689 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002690 request.getServicesCount(),
2691 NO_SENT_QUERY_COUNT);
Dave Plattfeff2af2014-03-07 14:48:22 -08002692 break;
2693 case NsdManager.RESOLVE_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002694 stopResolveService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002695 mMetrics.reportServiceResolutionStop(true /* isLegacy */, transactionId,
Paul Hu60149052023-07-31 14:26:08 +08002696 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Dave Plattfeff2af2014-03-07 14:48:22 -08002697 break;
2698 case NsdManager.REGISTER_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002699 unregisterService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002700 mMetrics.reportServiceUnregistration(true /* isLegacy */, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002701 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2702 NO_PACKET /* repliedRequestsCount */,
2703 NO_PACKET /* sentPacketCount */,
2704 0 /* conflictDuringProbingCount */,
2705 0 /* conflictAfterProbingCount */);
Dave Plattfeff2af2014-03-07 14:48:22 -08002706 break;
2707 default:
2708 break;
2709 }
2710 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002711 mClientRequests.clear();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002712 updateMulticastLock();
2713 }
2714
2715 /**
2716 * Returns true if this client has any Java backend request that requests one of the given
2717 * networks.
2718 */
2719 boolean hasAnyJavaBackendRequestForNetworks(@NonNull ArraySet<Network> networks) {
2720 for (int i = 0; i < mClientRequests.size(); i++) {
2721 final ClientRequest req = mClientRequests.valueAt(i);
2722 if (!(req instanceof JavaBackendClientRequest)) {
2723 continue;
2724 }
2725 final Network reqNetwork = ((JavaBackendClientRequest) mClientRequests.valueAt(i))
2726 .getRequestedNetwork();
2727 if (MdnsUtils.isAnyNetworkMatched(reqNetwork, networks)) {
2728 return true;
2729 }
2730 }
2731 return false;
Dave Plattfeff2af2014-03-07 14:48:22 -08002732 }
2733
Paul Hud44e1b72023-06-16 02:07:42 +00002734 // mClientRequests is a sparse array of client request id -> ClientRequest. For a given
2735 // transaction id, return the corresponding client request id.
2736 private int getClientRequestId(final int transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002737 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002738 if (mClientRequests.valueAt(i).mTransactionId == transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002739 return mClientRequests.keyAt(i);
2740 }
Christopher Lane74411222014-04-25 18:39:07 -07002741 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002742 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07002743 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002744
Paul Hub2e67d32023-04-18 05:50:14 +00002745 private void log(String message) {
2746 mClientLogs.log(message);
2747 }
2748
Paul Hu508a0122023-09-11 15:31:33 +08002749 private static boolean isLegacyClientRequest(@NonNull ClientRequest request) {
2750 return !(request instanceof DiscoveryManagerRequest)
2751 && !(request instanceof AdvertiserClientRequest);
2752 }
2753
Kangping Dong1f1a3792023-12-10 22:05:04 +08002754 void onDiscoverServicesStarted(int listenerKey, DiscoveryRequest discoveryRequest,
Paul Hu508a0122023-09-11 15:31:33 +08002755 ClientRequest request) {
2756 mMetrics.reportServiceDiscoveryStarted(
2757 isLegacyClientRequest(request), request.mTransactionId);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002758 try {
Kangping Dong1f1a3792023-12-10 22:05:04 +08002759 mCb.onDiscoverServicesStarted(listenerKey, discoveryRequest);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002760 } catch (RemoteException e) {
2761 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
2762 }
2763 }
Paul Hu508a0122023-09-11 15:31:33 +08002764 void onDiscoverServicesFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2765 onDiscoverServicesFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2766 0L /* durationMs */);
Paul Hu812e9212023-06-20 06:24:53 +00002767 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002768
Paul Hu508a0122023-09-11 15:31:33 +08002769 void onDiscoverServicesFailed(int listenerKey, int error, boolean isLegacy,
2770 int transactionId, long durationMs) {
2771 mMetrics.reportServiceDiscoveryFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002772 try {
2773 mCb.onDiscoverServicesFailed(listenerKey, error);
2774 } catch (RemoteException e) {
2775 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
2776 }
2777 }
2778
Paul Hu812e9212023-06-20 06:24:53 +00002779 void onServiceFound(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2780 request.onServiceFound(info.getServiceName());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002781 try {
2782 mCb.onServiceFound(listenerKey, info);
2783 } catch (RemoteException e) {
2784 Log.e(TAG, "Error calling onServiceFound(", e);
2785 }
2786 }
2787
Paul Hu812e9212023-06-20 06:24:53 +00002788 void onServiceLost(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2789 request.onServiceLost();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002790 try {
2791 mCb.onServiceLost(listenerKey, info);
2792 } catch (RemoteException e) {
2793 Log.e(TAG, "Error calling onServiceLost(", e);
2794 }
2795 }
2796
2797 void onStopDiscoveryFailed(int listenerKey, int error) {
2798 try {
2799 mCb.onStopDiscoveryFailed(listenerKey, error);
2800 } catch (RemoteException e) {
2801 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
2802 }
2803 }
2804
Paul Hu812e9212023-06-20 06:24:53 +00002805 void onStopDiscoverySucceeded(int listenerKey, ClientRequest request) {
2806 mMetrics.reportServiceDiscoveryStop(
Paul Hu508a0122023-09-11 15:31:33 +08002807 isLegacyClientRequest(request),
Paul Hu812e9212023-06-20 06:24:53 +00002808 request.mTransactionId,
2809 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2810 request.getFoundServiceCount(),
2811 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002812 request.getServicesCount(),
2813 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002814 try {
2815 mCb.onStopDiscoverySucceeded(listenerKey);
2816 } catch (RemoteException e) {
2817 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2818 }
2819 }
2820
Paul Hu508a0122023-09-11 15:31:33 +08002821 void onRegisterServiceFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2822 onRegisterServiceFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2823 0L /* durationMs */);
Paul Hu777ed052023-06-19 13:35:15 +00002824 }
2825
Paul Hu508a0122023-09-11 15:31:33 +08002826 void onRegisterServiceFailed(int listenerKey, int error, boolean isLegacy,
2827 int transactionId, long durationMs) {
2828 mMetrics.reportServiceRegistrationFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002829 try {
2830 mCb.onRegisterServiceFailed(listenerKey, error);
2831 } catch (RemoteException e) {
2832 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2833 }
2834 }
2835
Paul Hu508a0122023-09-11 15:31:33 +08002836 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info,
2837 ClientRequest request) {
2838 mMetrics.reportServiceRegistrationSucceeded(isLegacyClientRequest(request),
2839 request.mTransactionId,
2840 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002841 try {
2842 mCb.onRegisterServiceSucceeded(listenerKey, info);
2843 } catch (RemoteException e) {
2844 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2845 }
2846 }
2847
2848 void onUnregisterServiceFailed(int listenerKey, int error) {
2849 try {
2850 mCb.onUnregisterServiceFailed(listenerKey, error);
2851 } catch (RemoteException e) {
2852 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2853 }
2854 }
2855
Paul Hu508a0122023-09-11 15:31:33 +08002856 void onUnregisterServiceSucceeded(int listenerKey, ClientRequest request,
Paul Hu043bcd42023-07-14 16:38:25 +08002857 AdvertiserMetrics metrics) {
Paul Hu508a0122023-09-11 15:31:33 +08002858 mMetrics.reportServiceUnregistration(isLegacyClientRequest(request),
2859 request.mTransactionId,
2860 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hu043bcd42023-07-14 16:38:25 +08002861 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2862 metrics.mConflictDuringProbingCount, metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002863 try {
2864 mCb.onUnregisterServiceSucceeded(listenerKey);
2865 } catch (RemoteException e) {
2866 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2867 }
2868 }
2869
Paul Hu508a0122023-09-11 15:31:33 +08002870 void onResolveServiceFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2871 onResolveServiceFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2872 0L /* durationMs */);
Paul Hua6bc4632023-06-26 01:18:29 +00002873 }
2874
Paul Hu508a0122023-09-11 15:31:33 +08002875 void onResolveServiceFailed(int listenerKey, int error, boolean isLegacy,
2876 int transactionId, long durationMs) {
2877 mMetrics.reportServiceResolutionFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002878 try {
2879 mCb.onResolveServiceFailed(listenerKey, error);
2880 } catch (RemoteException e) {
2881 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2882 }
2883 }
2884
Paul Hua6bc4632023-06-26 01:18:29 +00002885 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info,
2886 ClientRequest request) {
2887 mMetrics.reportServiceResolved(
Paul Hu508a0122023-09-11 15:31:33 +08002888 isLegacyClientRequest(request),
Paul Hua6bc4632023-06-26 01:18:29 +00002889 request.mTransactionId,
2890 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hubad6fe92023-07-24 21:25:22 +08002891 request.isServiceFromCache(),
2892 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002893 try {
2894 mCb.onResolveServiceSucceeded(listenerKey, info);
2895 } catch (RemoteException e) {
2896 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2897 }
2898 }
Paul Hub58deb72022-12-26 09:24:42 +00002899
2900 void onStopResolutionFailed(int listenerKey, int error) {
2901 try {
2902 mCb.onStopResolutionFailed(listenerKey, error);
2903 } catch (RemoteException e) {
2904 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2905 }
2906 }
2907
Paul Hu60149052023-07-31 14:26:08 +08002908 void onStopResolutionSucceeded(int listenerKey, ClientRequest request) {
2909 mMetrics.reportServiceResolutionStop(
Paul Hu508a0122023-09-11 15:31:33 +08002910 isLegacyClientRequest(request),
Paul Hu60149052023-07-31 14:26:08 +08002911 request.mTransactionId,
2912 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hub58deb72022-12-26 09:24:42 +00002913 try {
2914 mCb.onStopResolutionSucceeded(listenerKey);
2915 } catch (RemoteException e) {
2916 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2917 }
2918 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002919
2920 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
Paul Huddce5912023-08-01 10:26:49 +08002921 mMetrics.reportServiceInfoCallbackRegistrationFailed(NO_TRANSACTION);
Paul Hu18aeccc2022-12-27 08:48:48 +00002922 try {
2923 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2924 } catch (RemoteException e) {
2925 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2926 }
2927 }
2928
Paul Huddce5912023-08-01 10:26:49 +08002929 void onServiceInfoCallbackRegistered(int transactionId) {
2930 mMetrics.reportServiceInfoCallbackRegistered(transactionId);
2931 }
2932
2933 void onServiceUpdated(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2934 request.onServiceFound(info.getServiceName());
Paul Hu18aeccc2022-12-27 08:48:48 +00002935 try {
2936 mCb.onServiceUpdated(listenerKey, info);
2937 } catch (RemoteException e) {
2938 Log.e(TAG, "Error calling onServiceUpdated", e);
2939 }
2940 }
2941
Paul Huddce5912023-08-01 10:26:49 +08002942 void onServiceUpdatedLost(int listenerKey, ClientRequest request) {
2943 request.onServiceLost();
Paul Hu18aeccc2022-12-27 08:48:48 +00002944 try {
2945 mCb.onServiceUpdatedLost(listenerKey);
2946 } catch (RemoteException e) {
2947 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2948 }
2949 }
2950
Paul Huddce5912023-08-01 10:26:49 +08002951 void onServiceInfoCallbackUnregistered(int listenerKey, ClientRequest request) {
2952 mMetrics.reportServiceInfoCallbackUnregistered(
2953 request.mTransactionId,
2954 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2955 request.getFoundServiceCount(),
2956 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002957 request.isServiceFromCache(),
2958 request.getSentQueryCount());
Paul Hu18aeccc2022-12-27 08:48:48 +00002959 try {
2960 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2961 } catch (RemoteException e) {
2962 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2963 }
2964 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002965 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002966}