blob: fc6c6e42124d5bf9aeb90dcac0329cc4cc86e43c [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 Huang33fa4d22023-02-14 22:59:37 +090019import static android.Manifest.permission.NETWORK_SETTINGS;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090020import static android.Manifest.permission.NETWORK_STACK;
paulhu2b9ed952022-02-10 21:58:32 +080021import static android.net.ConnectivityManager.NETID_UNSET;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090022import static android.net.NetworkCapabilities.TRANSPORT_VPN;
23import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090024import static android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK;
Paul Hu019621e2023-01-13 23:26:49 +080025import static android.net.nsd.NsdManager.MDNS_DISCOVERY_MANAGER_EVENT;
paulhu2b9ed952022-02-10 21:58:32 +080026import static android.net.nsd.NsdManager.MDNS_SERVICE_EVENT;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +090027import static android.net.nsd.NsdManager.RESOLVE_SERVICE_SUCCEEDED;
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +090028import static android.provider.DeviceConfig.NAMESPACE_TETHERING;
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090029import static com.android.modules.utils.build.SdkLevel.isAtLeastU;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090030import static com.android.networkstack.apishim.ConstantsShim.REGISTER_NSD_OFFLOAD_ENGINE;
Paul Hu043bcd42023-07-14 16:38:25 +080031import static com.android.server.connectivity.mdns.MdnsAdvertiser.AdvertiserMetrics;
32import static com.android.server.connectivity.mdns.MdnsConstants.NO_PACKET;
Yuyang Huangde802c82023-05-02 17:14:22 +090033import static com.android.server.connectivity.mdns.MdnsRecord.MAX_LABEL_LENGTH;
Paul Hucdef3532023-06-18 14:47:35 +000034import static com.android.server.connectivity.mdns.util.MdnsUtils.Clock;
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090035
Paul Hu23fa2022023-01-13 22:57:24 +080036import android.annotation.NonNull;
Paul Hu4bd98ef2023-01-12 13:42:07 +080037import android.annotation.Nullable;
Yuyang Huangfc831702023-08-21 17:48:48 +090038import android.annotation.RequiresApi;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090039import android.app.ActivityManager;
paulhua262cc12019-08-12 16:25:11 +080040import android.content.Context;
Irfan Sheriff75006652012-04-17 23:15:29 -070041import android.content.Intent;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090042import android.net.ConnectivityManager;
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +090043import android.net.INetd;
Paul Hu75069ed2023-01-14 00:31:09 +080044import android.net.InetAddresses;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090045import android.net.LinkProperties;
46import android.net.Network;
paulhu2b9ed952022-02-10 21:58:32 +080047import android.net.mdns.aidl.DiscoveryInfo;
48import android.net.mdns.aidl.GetAddressInfo;
49import android.net.mdns.aidl.IMDnsEventListener;
50import android.net.mdns.aidl.RegistrationInfo;
51import android.net.mdns.aidl.ResolutionInfo;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070052import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090053import android.net.nsd.INsdManagerCallback;
54import android.net.nsd.INsdServiceConnector;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090055import android.net.nsd.IOffloadEngine;
paulhu2b9ed952022-02-10 21:58:32 +080056import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070057import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080058import android.net.nsd.NsdServiceInfo;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090059import android.net.nsd.OffloadEngine;
60import android.net.nsd.OffloadServiceInfo;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090061import android.net.wifi.WifiManager;
Paul Hub2e67d32023-04-18 05:50:14 +000062import android.os.Binder;
Yuyang Huangfc831702023-08-21 17:48:48 +090063import android.os.Build;
Hugo Benichi803a2f02017-04-24 11:35:06 +090064import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080065import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090066import android.os.IBinder;
Paul Hu4bd98ef2023-01-12 13:42:07 +080067import android.os.Looper;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070068import android.os.Message;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090069import android.os.RemoteCallbackList;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090070import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070071import android.os.UserHandle;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090072import android.provider.DeviceConfig;
Paul Hu23fa2022023-01-13 22:57:24 +080073import android.text.TextUtils;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090074import android.util.ArraySet;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090075import android.util.Log;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +090076import android.util.Pair;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070077import android.util.SparseArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070078
paulhua262cc12019-08-12 16:25:11 +080079import com.android.internal.annotations.VisibleForTesting;
Paul Hub2e67d32023-04-18 05:50:14 +000080import com.android.internal.util.IndentingPrintWriter;
paulhua262cc12019-08-12 16:25:11 +080081import com.android.internal.util.State;
82import com.android.internal.util.StateMachine;
Paul Hucdef3532023-06-18 14:47:35 +000083import com.android.metrics.NetworkNsdReportedMetrics;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090084import com.android.modules.utils.build.SdkLevel;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090085import com.android.net.module.util.CollectionUtils;
Paul Hu4bd98ef2023-01-12 13:42:07 +080086import com.android.net.module.util.DeviceConfigUtils;
Yuyang Huanga6a6ff92023-04-24 13:33:34 +090087import com.android.net.module.util.InetAddressUtils;
paulhu3ffffe72021-09-16 10:15:22 +080088import com.android.net.module.util.PermissionUtils;
Paul Hub2e67d32023-04-18 05:50:14 +000089import com.android.net.module.util.SharedLog;
Paul Hu4bd98ef2023-01-12 13:42:07 +080090import com.android.server.connectivity.mdns.ExecutorProvider;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090091import com.android.server.connectivity.mdns.MdnsAdvertiser;
Paul Hu4bd98ef2023-01-12 13:42:07 +080092import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
Yuyang Huangb96a0712023-09-07 15:13:15 +090093import com.android.server.connectivity.mdns.MdnsFeatureFlags;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090094import com.android.server.connectivity.mdns.MdnsInterfaceSocket;
Paul Hu4bd98ef2023-01-12 13:42:07 +080095import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
Paul Hu23fa2022023-01-13 22:57:24 +080096import com.android.server.connectivity.mdns.MdnsSearchOptions;
97import com.android.server.connectivity.mdns.MdnsServiceBrowserListener;
98import com.android.server.connectivity.mdns.MdnsServiceInfo;
Paul Hu4bd98ef2023-01-12 13:42:07 +080099import com.android.server.connectivity.mdns.MdnsSocketProvider;
Yuyang Huangde802c82023-05-02 17:14:22 +0900100import com.android.server.connectivity.mdns.util.MdnsUtils;
paulhua262cc12019-08-12 16:25:11 +0800101
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700102import java.io.FileDescriptor;
103import java.io.PrintWriter;
Yuyang Huangaa0e9602023-03-17 12:43:09 +0900104import java.net.Inet6Address;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700105import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900106import java.net.NetworkInterface;
107import java.net.SocketException;
108import java.net.UnknownHostException;
Paul Hu2b865912023-03-06 14:27:53 +0800109import java.util.ArrayList;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900110import java.util.Arrays;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700111import java.util.HashMap;
Paul Hu23fa2022023-01-13 22:57:24 +0800112import java.util.List;
Paul Hu75069ed2023-01-14 00:31:09 +0800113import java.util.Map;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900114import java.util.Objects;
Paul Hu812e9212023-06-20 06:24:53 +0000115import java.util.Set;
Paul Hu23fa2022023-01-13 22:57:24 +0800116import java.util.regex.Matcher;
117import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700118
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700119/**
120 * Network Service Discovery Service handles remote service discovery operation requests by
121 * implementing the INsdManager interface.
122 *
123 * @hide
124 */
Yuyang Huangfc831702023-08-21 17:48:48 +0900125@RequiresApi(Build.VERSION_CODES.TIRAMISU)
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700126public class NsdService extends INsdManager.Stub {
127 private static final String TAG = "NsdService";
128 private static final String MDNS_TAG = "mDnsConnector";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900129 /**
130 * Enable discovery using the Java DiscoveryManager, instead of the legacy mdnsresponder
131 * implementation.
132 */
Paul Hu4bd98ef2023-01-12 13:42:07 +0800133 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +0800134 private static final String LOCAL_DOMAIN_NAME = "local";
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700135
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900136 /**
137 * Enable advertising using the Java MdnsAdvertiser, instead of the legacy mdnsresponder
138 * implementation.
139 */
140 private static final String MDNS_ADVERTISER_VERSION = "mdns_advertiser_version";
141
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900142 /**
143 * Comma-separated list of type:flag mappings indicating the flags to use to allowlist
144 * discovery/advertising using MdnsDiscoveryManager / MdnsAdvertiser for a given type.
145 *
146 * For example _mytype._tcp.local and _othertype._tcp.local would be configured with:
147 * _mytype._tcp:mytype,_othertype._tcp.local:othertype
148 *
149 * In which case the flags:
150 * "mdns_discovery_manager_allowlist_mytype_version",
151 * "mdns_advertiser_allowlist_mytype_version",
152 * "mdns_discovery_manager_allowlist_othertype_version",
153 * "mdns_advertiser_allowlist_othertype_version"
154 * would be used to toggle MdnsDiscoveryManager / MdnsAdvertiser for each type. The flags will
155 * be read with
Motomu Utsumi624aeb42023-08-15 15:52:27 +0900156 * {@link DeviceConfigUtils#isTetheringFeatureEnabled}
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900157 *
158 * @see #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX
159 * @see #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX
160 * @see #MDNS_ALLOWLIST_FLAG_SUFFIX
161 */
162 private static final String MDNS_TYPE_ALLOWLIST_FLAGS = "mdns_type_allowlist_flags";
163
164 private static final String MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX =
165 "mdns_discovery_manager_allowlist_";
166 private static final String MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX =
167 "mdns_advertiser_allowlist_";
168 private static final String MDNS_ALLOWLIST_FLAG_SUFFIX = "_version";
169
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900170 @VisibleForTesting
171 static final String MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
172 "mdns_config_running_app_active_importance_cutoff";
173 @VisibleForTesting
174 static final int DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
175 ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
176 private final int mRunningAppActiveImportanceCutoff;
177
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900178 public static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +0000179 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900180 private static final int IFACE_IDX_ANY = 0;
Paul Hu812e9212023-06-20 06:24:53 +0000181 private static final int MAX_SERVICES_COUNT_METRIC_PER_CLIENT = 100;
182 @VisibleForTesting
183 static final int NO_TRANSACTION = -1;
Paul Hubad6fe92023-07-24 21:25:22 +0800184 private static final int NO_SENT_QUERY_COUNT = 0;
185 private static final int DISCOVERY_QUERY_SENT_CALLBACK = 1000;
Paul Hu14667de2023-04-17 22:42:47 +0800186 private static final SharedLog LOGGER = new SharedLog("serviceDiscovery");
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700187
Hugo Benichi32be63d2017-04-05 14:06:11 +0900188 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900189 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +0800190 private final MDnsManager mMDnsManager;
191 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900192 @NonNull
193 private final Dependencies mDeps;
194 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800195 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900196 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800197 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900198 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800199 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900200 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900201 private final MdnsAdvertiser mAdvertiser;
Paul Hu777ed052023-06-19 13:35:15 +0000202 @NonNull
203 private final Clock mClock;
Paul Hu14667de2023-04-17 22:42:47 +0800204 private final SharedLog mServiceLogs = LOGGER.forSubComponent(TAG);
Paul Hu23fa2022023-01-13 22:57:24 +0800205 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800206 // state machine thread. If change this outside state machine, it will need to introduce
207 // synchronization.
208 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800209 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700210
211 /**
212 * Clients receiving asynchronous messages
213 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900214 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700215
Paul Hud44e1b72023-06-16 02:07:42 +0000216 /* A map from transaction(unique) id to client info */
217 private final SparseArray<ClientInfo> mTransactionIdToClientInfoMap = new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700218
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900219 // Note this is not final to avoid depending on the Wi-Fi service starting before NsdService
220 @Nullable
221 private WifiManager.MulticastLock mHeldMulticastLock;
222 // Fulfilled network requests that require the Wi-Fi lock: key is the obtained Network
223 // (non-null), value is the requested Network (nullable)
224 @NonNull
225 private final ArraySet<Network> mWifiLockRequiredNetworks = new ArraySet<>();
226 @NonNull
227 private final ArraySet<Integer> mRunningAppActiveUids = new ArraySet<>();
228
Luke Huang05298582021-06-13 16:52:05 +0000229 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700230
Hugo Benichi32be63d2017-04-05 14:06:11 +0900231 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700232 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800233 // The count of the connected legacy clients.
234 private int mLegacyClientCount = 0;
Paul Hub2e67d32023-04-18 05:50:14 +0000235 // The number of client that ever connected.
236 private int mClientNumberId = 1;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700237
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900238 private final RemoteCallbackList<IOffloadEngine> mOffloadEngines =
239 new RemoteCallbackList<>();
240
241 private static class OffloadEngineInfo {
242 @NonNull final String mInterfaceName;
243 final long mOffloadCapabilities;
244 final long mOffloadType;
245 @NonNull final IOffloadEngine mOffloadEngine;
246
247 OffloadEngineInfo(@NonNull IOffloadEngine offloadEngine,
248 @NonNull String interfaceName, long capabilities, long offloadType) {
249 this.mOffloadEngine = offloadEngine;
250 this.mInterfaceName = interfaceName;
251 this.mOffloadCapabilities = capabilities;
252 this.mOffloadType = offloadType;
253 }
254 }
255
Paul Hu812e9212023-06-20 06:24:53 +0000256 @VisibleForTesting
257 static class MdnsListener implements MdnsServiceBrowserListener {
Paul Hud44e1b72023-06-16 02:07:42 +0000258 protected final int mClientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800259 protected final int mTransactionId;
260 @NonNull
261 protected final NsdServiceInfo mReqServiceInfo;
262 @NonNull
263 protected final String mListenedServiceType;
264
Paul Hud44e1b72023-06-16 02:07:42 +0000265 MdnsListener(int clientRequestId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
Paul Hu23fa2022023-01-13 22:57:24 +0800266 @NonNull String listenedServiceType) {
Paul Hud44e1b72023-06-16 02:07:42 +0000267 mClientRequestId = clientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800268 mTransactionId = transactionId;
269 mReqServiceInfo = reqServiceInfo;
270 mListenedServiceType = listenedServiceType;
271 }
272
273 @NonNull
274 public String getListenedServiceType() {
275 return mListenedServiceType;
276 }
277
278 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000279 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
280 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800281
282 @Override
283 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
284
285 @Override
286 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
287
288 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000289 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
290 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800291
292 @Override
293 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
294
295 @Override
296 public void onSearchStoppedWithError(int error) { }
297
298 @Override
299 public void onSearchFailedToStart() { }
300
301 @Override
Paul Hubad6fe92023-07-24 21:25:22 +0800302 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
303 int sentQueryTransactionId) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800304
305 @Override
306 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
307 }
308
309 private class DiscoveryListener extends MdnsListener {
310
Paul Hud44e1b72023-06-16 02:07:42 +0000311 DiscoveryListener(int clientRequestId, int transactionId,
312 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
313 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800314 }
315
316 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000317 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
318 boolean isServiceFromCache) {
Paul Hu019621e2023-01-13 23:26:49 +0800319 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
320 NsdManager.SERVICE_FOUND,
Paul Hua6bc4632023-06-26 01:18:29 +0000321 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu23fa2022023-01-13 22:57:24 +0800322 }
323
324 @Override
325 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800326 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
327 NsdManager.SERVICE_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000328 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800329 }
Paul Hubad6fe92023-07-24 21:25:22 +0800330
331 @Override
332 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
333 int sentQueryTransactionId) {
334 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
335 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
336 }
Paul Hu23fa2022023-01-13 22:57:24 +0800337 }
338
Paul Hu75069ed2023-01-14 00:31:09 +0800339 private class ResolutionListener extends MdnsListener {
340
Paul Hud44e1b72023-06-16 02:07:42 +0000341 ResolutionListener(int clientRequestId, int transactionId,
342 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
343 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800344 }
345
346 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000347 public void onServiceFound(MdnsServiceInfo serviceInfo, boolean isServiceFromCache) {
Paul Hu75069ed2023-01-14 00:31:09 +0800348 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
349 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
Paul Hua6bc4632023-06-26 01:18:29 +0000350 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu75069ed2023-01-14 00:31:09 +0800351 }
Paul Hubad6fe92023-07-24 21:25:22 +0800352
353 @Override
354 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
355 int sentQueryTransactionId) {
356 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
357 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
358 }
Paul Hu75069ed2023-01-14 00:31:09 +0800359 }
360
Paul Hu30bd70d2023-02-07 13:20:56 +0000361 private class ServiceInfoListener extends MdnsListener {
362
Paul Hud44e1b72023-06-16 02:07:42 +0000363 ServiceInfoListener(int clientRequestId, int transactionId,
364 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
365 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +0000366 }
367
368 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000369 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
370 boolean isServiceFromCache) {
Paul Hu30bd70d2023-02-07 13:20:56 +0000371 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
372 NsdManager.SERVICE_UPDATED,
Paul Hua6bc4632023-06-26 01:18:29 +0000373 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu30bd70d2023-02-07 13:20:56 +0000374 }
375
376 @Override
377 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) {
378 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
379 NsdManager.SERVICE_UPDATED,
Paul Hud44e1b72023-06-16 02:07:42 +0000380 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000381 }
382
383 @Override
384 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) {
385 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
386 NsdManager.SERVICE_UPDATED_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000387 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000388 }
Paul Hubad6fe92023-07-24 21:25:22 +0800389
390 @Override
391 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
392 int sentQueryTransactionId) {
393 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
394 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
395 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000396 }
397
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900398 private class SocketRequestMonitor implements MdnsSocketProvider.SocketRequestMonitor {
399 @Override
400 public void onSocketRequestFulfilled(@Nullable Network socketNetwork,
401 @NonNull MdnsInterfaceSocket socket, @NonNull int[] transports) {
402 // The network may be null for Wi-Fi SoftAp interfaces (tethering), but there is no APF
403 // filtering on such interfaces, so taking the multicast lock is not necessary to
404 // disable APF filtering of multicast.
405 if (socketNetwork == null
406 || !CollectionUtils.contains(transports, TRANSPORT_WIFI)
407 || CollectionUtils.contains(transports, TRANSPORT_VPN)) {
408 return;
409 }
410
411 if (mWifiLockRequiredNetworks.add(socketNetwork)) {
412 updateMulticastLock();
413 }
414 }
415
416 @Override
417 public void onSocketDestroyed(@Nullable Network socketNetwork,
418 @NonNull MdnsInterfaceSocket socket) {
419 if (mWifiLockRequiredNetworks.remove(socketNetwork)) {
420 updateMulticastLock();
421 }
422 }
423 }
424
425 private class UidImportanceListener implements ActivityManager.OnUidImportanceListener {
426 private final Handler mHandler;
427
428 private UidImportanceListener(Handler handler) {
429 mHandler = handler;
430 }
431
432 @Override
433 public void onUidImportance(int uid, int importance) {
434 mHandler.post(() -> handleUidImportanceChanged(uid, importance));
435 }
436 }
437
438 private void handleUidImportanceChanged(int uid, int importance) {
439 // Lower importance values are more "important"
440 final boolean modified = importance <= mRunningAppActiveImportanceCutoff
441 ? mRunningAppActiveUids.add(uid)
442 : mRunningAppActiveUids.remove(uid);
443 if (modified) {
444 updateMulticastLock();
445 }
446 }
447
448 /**
449 * Take or release the lock based on updated internal state.
450 *
451 * This determines whether the lock needs to be held based on
452 * {@link #mWifiLockRequiredNetworks}, {@link #mRunningAppActiveUids} and
453 * {@link ClientInfo#mClientRequests}, so it must be called after any of the these have been
454 * updated.
455 */
456 private void updateMulticastLock() {
457 final int needsLockUid = getMulticastLockNeededUid();
458 if (needsLockUid >= 0 && mHeldMulticastLock == null) {
459 final WifiManager wm = mContext.getSystemService(WifiManager.class);
460 if (wm == null) {
461 Log.wtf(TAG, "Got a TRANSPORT_WIFI network without WifiManager");
462 return;
463 }
464 mHeldMulticastLock = wm.createMulticastLock(TAG);
465 mHeldMulticastLock.acquire();
466 mServiceLogs.log("Taking multicast lock for uid " + needsLockUid);
467 } else if (needsLockUid < 0 && mHeldMulticastLock != null) {
468 mHeldMulticastLock.release();
469 mHeldMulticastLock = null;
470 mServiceLogs.log("Released multicast lock");
471 }
472 }
473
474 /**
475 * @return The UID of an app requiring the multicast lock, or -1 if none.
476 */
477 private int getMulticastLockNeededUid() {
478 if (mWifiLockRequiredNetworks.size() == 0) {
479 // Return early if NSD is not active, or not on any relevant network
480 return -1;
481 }
Paul Hud44e1b72023-06-16 02:07:42 +0000482 for (int i = 0; i < mTransactionIdToClientInfoMap.size(); i++) {
483 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.valueAt(i);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900484 if (!mRunningAppActiveUids.contains(clientInfo.mUid)) {
485 // Ignore non-active UIDs
486 continue;
487 }
488
489 if (clientInfo.hasAnyJavaBackendRequestForNetworks(mWifiLockRequiredNetworks)) {
490 return clientInfo.mUid;
491 }
492 }
493 return -1;
494 }
495
Paul Hu019621e2023-01-13 23:26:49 +0800496 /**
497 * Data class of mdns service callback information.
498 */
499 private static class MdnsEvent {
Paul Hud44e1b72023-06-16 02:07:42 +0000500 final int mClientRequestId;
Paul Hubad6fe92023-07-24 21:25:22 +0800501 @Nullable
Paul Hu019621e2023-01-13 23:26:49 +0800502 final MdnsServiceInfo mMdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000503 final boolean mIsServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800504
Paul Hubad6fe92023-07-24 21:25:22 +0800505 MdnsEvent(int clientRequestId) {
506 this(clientRequestId, null /* mdnsServiceInfo */, false /* isServiceFromCache */);
507 }
508
509 MdnsEvent(int clientRequestId, @Nullable MdnsServiceInfo mdnsServiceInfo) {
Paul Hua6bc4632023-06-26 01:18:29 +0000510 this(clientRequestId, mdnsServiceInfo, false /* isServiceFromCache */);
511 }
512
Paul Hubad6fe92023-07-24 21:25:22 +0800513 MdnsEvent(int clientRequestId, @Nullable MdnsServiceInfo mdnsServiceInfo,
Paul Hua6bc4632023-06-26 01:18:29 +0000514 boolean isServiceFromCache) {
Paul Hud44e1b72023-06-16 02:07:42 +0000515 mClientRequestId = clientRequestId;
Paul Hu019621e2023-01-13 23:26:49 +0800516 mMdnsServiceInfo = mdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000517 mIsServiceFromCache = isServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800518 }
519 }
520
Irfan Sheriff75006652012-04-17 23:15:29 -0700521 private class NsdStateMachine extends StateMachine {
522
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700523 private final DefaultState mDefaultState = new DefaultState();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700524 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700525
526 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700527 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900528 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700529 }
530
Luke Huang92860f92021-06-23 06:29:30 +0000531 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800532 if (mIsDaemonStarted) {
533 if (DBG) Log.d(TAG, "Daemon is already started.");
534 return;
535 }
536 mMDnsManager.registerEventListener(mMDnsEventCallback);
537 mMDnsManager.startDaemon();
538 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000539 maybeScheduleStop();
Paul Hub2e67d32023-04-18 05:50:14 +0000540 mServiceLogs.log("Start mdns_responder daemon");
Luke Huang05298582021-06-13 16:52:05 +0000541 }
542
paulhu2b9ed952022-02-10 21:58:32 +0800543 private void maybeStopDaemon() {
544 if (!mIsDaemonStarted) {
545 if (DBG) Log.d(TAG, "Daemon has not been started.");
546 return;
547 }
548 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
549 mMDnsManager.stopDaemon();
550 mIsDaemonStarted = false;
Paul Hub2e67d32023-04-18 05:50:14 +0000551 mServiceLogs.log("Stop mdns_responder daemon");
paulhu2b9ed952022-02-10 21:58:32 +0800552 }
553
Luke Huang92860f92021-06-23 06:29:30 +0000554 private boolean isAnyRequestActive() {
Paul Hud44e1b72023-06-16 02:07:42 +0000555 return mTransactionIdToClientInfoMap.size() != 0;
Luke Huang92860f92021-06-23 06:29:30 +0000556 }
557
558 private void scheduleStop() {
559 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
560 }
561 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800562 // The native daemon should stay alive and can't be cleanup
563 // if any legacy client connected.
564 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000565 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000566 }
567 }
568
Luke Huang92860f92021-06-23 06:29:30 +0000569 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000570 this.removeMessages(NsdManager.DAEMON_CLEANUP);
571 }
572
Paul Hu23fa2022023-01-13 22:57:24 +0800573 private void maybeStartMonitoringSockets() {
574 if (mIsMonitoringSocketsStarted) {
575 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
576 return;
577 }
578
579 mMdnsSocketProvider.startMonitoringSockets();
580 mIsMonitoringSocketsStarted = true;
581 }
582
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900583 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
584 if (!mIsMonitoringSocketsStarted) return;
585 if (isAnyRequestActive()) return;
586
Paul Hu58f20602023-02-18 11:41:07 +0800587 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800588 mIsMonitoringSocketsStarted = false;
589 }
590
Hugo Benichi803a2f02017-04-24 11:35:06 +0900591 NsdStateMachine(String name, Handler handler) {
592 super(name, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700593 addState(mDefaultState);
Irfan Sheriff75006652012-04-17 23:15:29 -0700594 addState(mEnabledState, mDefaultState);
paulhu5568f452021-11-30 13:31:29 +0800595 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900596 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700597 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700598 }
599
600 class DefaultState extends State {
601 @Override
602 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900603 final ClientInfo cInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000604 final int clientRequestId = msg.arg2;
Irfan Sheriff75006652012-04-17 23:15:29 -0700605 switch (msg.what) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900606 case NsdManager.REGISTER_CLIENT:
Paul Hu2e0a88c2023-03-09 16:05:01 +0800607 final ConnectorArgs arg = (ConnectorArgs) msg.obj;
608 final INsdManagerCallback cb = arg.callback;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900609 try {
Paul Hu2e0a88c2023-03-09 16:05:01 +0800610 cb.asBinder().linkToDeath(arg.connector, 0);
Paul Hub2e67d32023-04-18 05:50:14 +0000611 final String tag = "Client" + arg.uid + "-" + mClientNumberId++;
Paul Hu777ed052023-06-19 13:35:15 +0000612 final NetworkNsdReportedMetrics metrics =
613 mDeps.makeNetworkNsdReportedMetrics(
614 !arg.useJavaBackend, (int) mClock.elapsedRealtime());
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900615 cInfo = new ClientInfo(cb, arg.uid, arg.useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +0000616 mServiceLogs.forSubComponent(tag), metrics);
Paul Hu2e0a88c2023-03-09 16:05:01 +0800617 mClients.put(arg.connector, cInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900618 } catch (RemoteException e) {
Paul Hud44e1b72023-06-16 02:07:42 +0000619 Log.w(TAG, "Client request id " + clientRequestId
620 + " has already died");
Irfan Sheriff75006652012-04-17 23:15:29 -0700621 }
622 break;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900623 case NsdManager.UNREGISTER_CLIENT:
624 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
625 cInfo = mClients.remove(connector);
Dave Plattfeff2af2014-03-07 14:48:22 -0800626 if (cInfo != null) {
627 cInfo.expungeAllRequests();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900628 if (cInfo.isPreSClient()) {
Luke Huangf7277ed2021-07-12 21:15:10 +0800629 mLegacyClientCount -= 1;
630 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800631 }
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900632 maybeStopMonitoringSocketsIfNoActiveRequest();
Luke Huangf7277ed2021-07-12 21:15:10 +0800633 maybeScheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700634 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700635 case NsdManager.DISCOVER_SERVICES:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900636 cInfo = getClientInfoForReply(msg);
637 if (cInfo != null) {
Paul Hu812e9212023-06-20 06:24:53 +0000638 cInfo.onDiscoverServicesFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000639 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900640 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700641 break;
642 case NsdManager.STOP_DISCOVERY:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900643 cInfo = getClientInfoForReply(msg);
644 if (cInfo != null) {
645 cInfo.onStopDiscoveryFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000646 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900647 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700648 break;
649 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900650 cInfo = getClientInfoForReply(msg);
651 if (cInfo != null) {
Paul Hu777ed052023-06-19 13:35:15 +0000652 cInfo.onRegisterServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000653 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900654 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700655 break;
656 case NsdManager.UNREGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900657 cInfo = getClientInfoForReply(msg);
658 if (cInfo != null) {
659 cInfo.onUnregisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000660 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900661 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700662 break;
663 case NsdManager.RESOLVE_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900664 cInfo = getClientInfoForReply(msg);
665 if (cInfo != null) {
Paul Hua6bc4632023-06-26 01:18:29 +0000666 cInfo.onResolveServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000667 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900668 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700669 break;
Paul Hub58deb72022-12-26 09:24:42 +0000670 case NsdManager.STOP_RESOLUTION:
671 cInfo = getClientInfoForReply(msg);
672 if (cInfo != null) {
673 cInfo.onStopResolutionFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000674 clientRequestId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hub58deb72022-12-26 09:24:42 +0000675 }
676 break;
Paul Hu18aeccc2022-12-27 08:48:48 +0000677 case NsdManager.REGISTER_SERVICE_CALLBACK:
678 cInfo = getClientInfoForReply(msg);
679 if (cInfo != null) {
680 cInfo.onServiceInfoCallbackRegistrationFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000681 clientRequestId, NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +0000682 }
683 break;
Luke Huang05298582021-06-13 16:52:05 +0000684 case NsdManager.DAEMON_CLEANUP:
paulhu2b9ed952022-02-10 21:58:32 +0800685 maybeStopDaemon();
Luke Huang05298582021-06-13 16:52:05 +0000686 break;
Luke Huangf7277ed2021-07-12 21:15:10 +0800687 // This event should be only sent by the legacy (target SDK < S) clients.
688 // Mark the sending client as legacy.
689 case NsdManager.DAEMON_STARTUP:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900690 cInfo = getClientInfoForReply(msg);
Luke Huangf7277ed2021-07-12 21:15:10 +0800691 if (cInfo != null) {
692 cancelStop();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900693 cInfo.setPreSClient();
Luke Huangf7277ed2021-07-12 21:15:10 +0800694 mLegacyClientCount += 1;
695 maybeStartDaemon();
696 }
697 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700698 default:
paulhub2225702021-11-17 09:35:33 +0800699 Log.e(TAG, "Unhandled " + msg);
Irfan Sheriff75006652012-04-17 23:15:29 -0700700 return NOT_HANDLED;
701 }
702 return HANDLED;
703 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900704
705 private ClientInfo getClientInfoForReply(Message msg) {
706 final ListenerArgs args = (ListenerArgs) msg.obj;
707 return mClients.get(args.connector);
708 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700709 }
710
Irfan Sheriff75006652012-04-17 23:15:29 -0700711 class EnabledState extends State {
712 @Override
713 public void enter() {
714 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700715 }
716
717 @Override
718 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000719 // TODO: it is incorrect to stop the daemon without expunging all requests
720 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000721 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700722 }
723
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700724 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900725 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800726 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700727 return true;
728 }
729 return false;
730 }
731
Paul Hud44e1b72023-06-16 02:07:42 +0000732 private void storeLegacyRequestMap(int clientRequestId, int transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +0000733 ClientInfo clientInfo, int what, long startTimeMs) {
734 clientInfo.mClientRequests.put(clientRequestId,
735 new LegacyClientRequest(transactionId, what, startTimeMs));
Paul Hud44e1b72023-06-16 02:07:42 +0000736 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000737 // Remove the cleanup event because here comes a new request.
738 cancelStop();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700739 }
740
Paul Hud44e1b72023-06-16 02:07:42 +0000741 private void storeAdvertiserRequestMap(int clientRequestId, int transactionId,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900742 ClientInfo clientInfo, @Nullable Network requestedNetwork) {
Paul Hu777ed052023-06-19 13:35:15 +0000743 clientInfo.mClientRequests.put(clientRequestId, new AdvertiserClientRequest(
Paul Hu812e9212023-06-20 06:24:53 +0000744 transactionId, requestedNetwork, mClock.elapsedRealtime()));
Paul Hud44e1b72023-06-16 02:07:42 +0000745 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900746 updateMulticastLock();
Paul Hu23fa2022023-01-13 22:57:24 +0800747 }
748
Paul Hud44e1b72023-06-16 02:07:42 +0000749 private void removeRequestMap(
750 int clientRequestId, int transactionId, ClientInfo clientInfo) {
751 final ClientRequest existing = clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900752 if (existing == null) return;
Paul Hud44e1b72023-06-16 02:07:42 +0000753 clientInfo.mClientRequests.remove(clientRequestId);
754 mTransactionIdToClientInfoMap.remove(transactionId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900755
756 if (existing instanceof LegacyClientRequest) {
757 maybeScheduleStop();
758 } else {
759 maybeStopMonitoringSocketsIfNoActiveRequest();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900760 updateMulticastLock();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900761 }
762 }
763
Paul Hud44e1b72023-06-16 02:07:42 +0000764 private void storeDiscoveryManagerRequestMap(int clientRequestId, int transactionId,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900765 MdnsListener listener, ClientInfo clientInfo,
766 @Nullable Network requestedNetwork) {
Paul Hu777ed052023-06-19 13:35:15 +0000767 clientInfo.mClientRequests.put(clientRequestId, new DiscoveryManagerRequest(
Paul Hu812e9212023-06-20 06:24:53 +0000768 transactionId, listener, requestedNetwork, mClock.elapsedRealtime()));
Paul Hud44e1b72023-06-16 02:07:42 +0000769 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900770 updateMulticastLock();
Paul Hu23fa2022023-01-13 22:57:24 +0800771 }
772
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900773 /**
774 * Truncate a service name to up to 63 UTF-8 bytes.
775 *
776 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
777 * names used in registerService follows historical behavior (see mdnsresponder
778 * handle_regservice_request).
779 */
780 @NonNull
781 private String truncateServiceName(@NonNull String originalName) {
Yuyang Huangde802c82023-05-02 17:14:22 +0900782 return MdnsUtils.truncateServiceName(originalName, MAX_LABEL_LENGTH);
Paul Hu23fa2022023-01-13 22:57:24 +0800783 }
784
Paul Hud44e1b72023-06-16 02:07:42 +0000785 private void stopDiscoveryManagerRequest(ClientRequest request, int clientRequestId,
786 int transactionId, ClientInfo clientInfo) {
Paul Hue4f5f252023-02-16 21:13:47 +0800787 clientInfo.unregisterMdnsListenerFromRequest(request);
Paul Hud44e1b72023-06-16 02:07:42 +0000788 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hue4f5f252023-02-16 21:13:47 +0800789 }
790
Irfan Sheriff75006652012-04-17 23:15:29 -0700791 @Override
792 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900793 final ClientInfo clientInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000794 final int transactionId;
795 final int clientRequestId = msg.arg2;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900796 final ListenerArgs args;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900797 final OffloadEngineInfo offloadEngineInfo;
Irfan Sheriff75006652012-04-17 23:15:29 -0700798 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800799 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800800 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900801 args = (ListenerArgs) msg.obj;
802 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000803 // If the binder death notification for a INsdManagerCallback was received
804 // before any calls are received by NsdService, the clientInfo would be
805 // cleared and cause NPE. Add a null check here to prevent this corner case.
806 if (clientInfo == null) {
807 Log.e(TAG, "Unknown connector in discovery");
808 break;
809 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700810
811 if (requestLimitReached(clientInfo)) {
Paul Hu812e9212023-06-20 06:24:53 +0000812 clientInfo.onDiscoverServicesFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000813 clientRequestId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriff75006652012-04-17 23:15:29 -0700814 break;
815 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700816
Paul Hu23fa2022023-01-13 22:57:24 +0800817 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000818 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900819 final Pair<String, String> typeAndSubtype =
820 parseTypeAndSubtype(info.getServiceType());
821 final String serviceType = typeAndSubtype == null
822 ? null : typeAndSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800823 if (clientInfo.mUseJavaBackend
824 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900825 || useDiscoveryManagerForType(serviceType)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800826 if (serviceType == null) {
Paul Hu812e9212023-06-20 06:24:53 +0000827 clientInfo.onDiscoverServicesFailedImmediately(
828 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu23fa2022023-01-13 22:57:24 +0800829 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700830 }
Paul Hu23fa2022023-01-13 22:57:24 +0800831
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900832 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800833 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +0000834 final MdnsListener listener = new DiscoveryListener(clientRequestId,
835 transactionId, info, listenServiceType);
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900836 final MdnsSearchOptions.Builder optionsBuilder =
837 MdnsSearchOptions.newBuilder()
838 .setNetwork(info.getNetwork())
Yuyang Huangff963222023-06-01 18:42:42 +0900839 .setRemoveExpiredService(true)
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900840 .setIsPassiveMode(true);
841 if (typeAndSubtype.second != null) {
842 // The parsing ensures subtype starts with an underscore.
843 // MdnsSearchOptions expects the underscore to not be present.
844 optionsBuilder.addSubtype(typeAndSubtype.second.substring(1));
845 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900846 mMdnsDiscoveryManager.registerListener(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900847 listenServiceType, listener, optionsBuilder.build());
Paul Hud44e1b72023-06-16 02:07:42 +0000848 storeDiscoveryManagerRequestMap(clientRequestId, transactionId,
849 listener, clientInfo, info.getNetwork());
Paul Hu812e9212023-06-20 06:24:53 +0000850 clientInfo.onDiscoverServicesStarted(
851 clientRequestId, info, transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +0000852 clientInfo.log("Register a DiscoveryListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +0000853 + " for service type:" + listenServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700854 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800855 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000856 if (discoverServices(transactionId, info)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800857 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +0000858 Log.d(TAG, "Discover " + msg.arg2 + " " + transactionId
Paul Hu23fa2022023-01-13 22:57:24 +0800859 + info.getServiceType());
860 }
Paul Hua6bc4632023-06-26 01:18:29 +0000861 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
862 msg.what, mClock.elapsedRealtime());
Paul Hu812e9212023-06-20 06:24:53 +0000863 clientInfo.onDiscoverServicesStarted(
864 clientRequestId, info, transactionId);
Paul Hu23fa2022023-01-13 22:57:24 +0800865 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000866 stopServiceDiscovery(transactionId);
Paul Hu812e9212023-06-20 06:24:53 +0000867 clientInfo.onDiscoverServicesFailedImmediately(
868 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu23fa2022023-01-13 22:57:24 +0800869 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700870 }
871 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800872 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900873 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800874 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900875 args = (ListenerArgs) msg.obj;
876 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000877 // If the binder death notification for a INsdManagerCallback was received
878 // before any calls are received by NsdService, the clientInfo would be
879 // cleared and cause NPE. Add a null check here to prevent this corner case.
880 if (clientInfo == null) {
881 Log.e(TAG, "Unknown connector in stop discovery");
882 break;
883 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700884
Paul Hud44e1b72023-06-16 02:07:42 +0000885 final ClientRequest request =
886 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900887 if (request == null) {
888 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700889 break;
890 }
Paul Hud44e1b72023-06-16 02:07:42 +0000891 transactionId = request.mTransactionId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900892 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
893 // point, so this needs to check the type of the original request to
894 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900895 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +0000896 stopDiscoveryManagerRequest(
897 request, clientRequestId, transactionId, clientInfo);
Paul Hu812e9212023-06-20 06:24:53 +0000898 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000899 clientInfo.log("Unregister the DiscoveryListener " + transactionId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700900 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000901 removeRequestMap(clientRequestId, transactionId, clientInfo);
902 if (stopServiceDiscovery(transactionId)) {
Paul Hu812e9212023-06-20 06:24:53 +0000903 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hu23fa2022023-01-13 22:57:24 +0800904 } else {
905 clientInfo.onStopDiscoveryFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000906 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu23fa2022023-01-13 22:57:24 +0800907 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700908 }
909 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900910 }
911 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800912 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900913 args = (ListenerArgs) msg.obj;
914 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000915 // If the binder death notification for a INsdManagerCallback was received
916 // before any calls are received by NsdService, the clientInfo would be
917 // cleared and cause NPE. Add a null check here to prevent this corner case.
918 if (clientInfo == null) {
919 Log.e(TAG, "Unknown connector in registration");
920 break;
921 }
922
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700923 if (requestLimitReached(clientInfo)) {
Paul Hu777ed052023-06-19 13:35:15 +0000924 clientInfo.onRegisterServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000925 clientRequestId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700926 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700927 }
928
Paul Hud44e1b72023-06-16 02:07:42 +0000929 transactionId = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900930 final NsdServiceInfo serviceInfo = args.serviceInfo;
931 final String serviceType = serviceInfo.getServiceType();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900932 final Pair<String, String> typeSubtype = parseTypeAndSubtype(serviceType);
933 final String registerServiceType = typeSubtype == null
934 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800935 if (clientInfo.mUseJavaBackend
936 || mDeps.isMdnsAdvertiserEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900937 || useAdvertiserForType(registerServiceType)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900938 if (registerServiceType == null) {
939 Log.e(TAG, "Invalid service type: " + serviceType);
Paul Hu777ed052023-06-19 13:35:15 +0000940 clientInfo.onRegisterServiceFailedImmediately(
941 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900942 break;
943 }
944 serviceInfo.setServiceType(registerServiceType);
945 serviceInfo.setServiceName(truncateServiceName(
946 serviceInfo.getServiceName()));
947
948 maybeStartMonitoringSockets();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900949 // TODO: pass in the subtype as well. Including the subtype in the
950 // service type would generate service instance names like
951 // Name._subtype._sub._type._tcp, which is incorrect
952 // (it should be Name._type._tcp).
Paul Hud44e1b72023-06-16 02:07:42 +0000953 mAdvertiser.addService(transactionId, serviceInfo, typeSubtype.second);
954 storeAdvertiserRequestMap(clientRequestId, transactionId, clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900955 serviceInfo.getNetwork());
Irfan Sheriff75006652012-04-17 23:15:29 -0700956 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900957 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000958 if (registerService(transactionId, serviceInfo)) {
959 if (DBG) {
960 Log.d(TAG, "Register " + clientRequestId
961 + " " + transactionId);
962 }
Paul Hua6bc4632023-06-26 01:18:29 +0000963 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
964 msg.what, mClock.elapsedRealtime());
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900965 // Return success after mDns reports success
966 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000967 unregisterService(transactionId);
Paul Hu777ed052023-06-19 13:35:15 +0000968 clientInfo.onRegisterServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000969 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900970 }
971
Irfan Sheriff75006652012-04-17 23:15:29 -0700972 }
973 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900974 }
975 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800976 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900977 args = (ListenerArgs) msg.obj;
978 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000979 // If the binder death notification for a INsdManagerCallback was received
980 // before any calls are received by NsdService, the clientInfo would be
981 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900982 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800983 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700984 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700985 }
Paul Hud44e1b72023-06-16 02:07:42 +0000986 final ClientRequest request =
987 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900988 if (request == null) {
989 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
990 break;
991 }
Paul Hud44e1b72023-06-16 02:07:42 +0000992 transactionId = request.mTransactionId;
993 removeRequestMap(clientRequestId, transactionId, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900994
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900995 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
996 // so this needs to check the type of the original request to unregister
997 // instead of looking at the flag value.
Paul Hu812e9212023-06-20 06:24:53 +0000998 final long stopTimeMs = mClock.elapsedRealtime();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900999 if (request instanceof AdvertiserClientRequest) {
Paul Hu043bcd42023-07-14 16:38:25 +08001000 final AdvertiserMetrics metrics =
1001 mAdvertiser.getAdvertiserMetrics(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00001002 mAdvertiser.removeService(transactionId);
Paul Hu777ed052023-06-19 13:35:15 +00001003 clientInfo.onUnregisterServiceSucceeded(clientRequestId, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08001004 request.calculateRequestDurationMs(stopTimeMs), metrics);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001005 } else {
Paul Hud44e1b72023-06-16 02:07:42 +00001006 if (unregisterService(transactionId)) {
Paul Hu777ed052023-06-19 13:35:15 +00001007 clientInfo.onUnregisterServiceSucceeded(clientRequestId,
Paul Hu812e9212023-06-20 06:24:53 +00001008 transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08001009 request.calculateRequestDurationMs(stopTimeMs),
1010 new AdvertiserMetrics(NO_PACKET /* repliedRequestsCount */,
1011 NO_PACKET /* sentPacketCount */,
1012 0 /* conflictDuringProbingCount */,
1013 0 /* conflictAfterProbingCount */));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001014 } else {
1015 clientInfo.onUnregisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001016 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001017 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001018 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001019 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001020 }
Paul Hu75069ed2023-01-14 00:31:09 +08001021 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +08001022 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001023 args = (ListenerArgs) msg.obj;
1024 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +00001025 // If the binder death notification for a INsdManagerCallback was received
1026 // before any calls are received by NsdService, the clientInfo would be
1027 // cleared and cause NPE. Add a null check here to prevent this corner case.
1028 if (clientInfo == null) {
1029 Log.e(TAG, "Unknown connector in resolution");
1030 break;
1031 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001032
Paul Hu75069ed2023-01-14 00:31:09 +08001033 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001034 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001035 final Pair<String, String> typeSubtype =
1036 parseTypeAndSubtype(info.getServiceType());
1037 final String serviceType = typeSubtype == null
1038 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001039 if (clientInfo.mUseJavaBackend
1040 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001041 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +08001042 if (serviceType == null) {
Paul Hua6bc4632023-06-26 01:18:29 +00001043 clientInfo.onResolveServiceFailedImmediately(
1044 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu75069ed2023-01-14 00:31:09 +08001045 break;
1046 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001047 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +08001048
1049 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001050 final MdnsListener listener = new ResolutionListener(clientRequestId,
1051 transactionId, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +08001052 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1053 .setNetwork(info.getNetwork())
1054 .setIsPassiveMode(true)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +09001055 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001056 .setRemoveExpiredService(true)
Paul Hu75069ed2023-01-14 00:31:09 +08001057 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001058 mMdnsDiscoveryManager.registerListener(
1059 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001060 storeDiscoveryManagerRequestMap(clientRequestId, transactionId,
1061 listener, clientInfo, info.getNetwork());
1062 clientInfo.log("Register a ResolutionListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001063 + " for service type:" + resolveServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -07001064 } else {
Paul Hu75069ed2023-01-14 00:31:09 +08001065 if (clientInfo.mResolvedService != null) {
Paul Hua6bc4632023-06-26 01:18:29 +00001066 clientInfo.onResolveServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +00001067 clientRequestId, NsdManager.FAILURE_ALREADY_ACTIVE);
Paul Hu75069ed2023-01-14 00:31:09 +08001068 break;
1069 }
1070
1071 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +00001072 if (resolveService(transactionId, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +08001073 clientInfo.mResolvedService = new NsdServiceInfo();
Paul Hua6bc4632023-06-26 01:18:29 +00001074 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
1075 msg.what, mClock.elapsedRealtime());
Paul Hu75069ed2023-01-14 00:31:09 +08001076 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001077 clientInfo.onResolveServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +00001078 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu75069ed2023-01-14 00:31:09 +08001079 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001080 }
1081 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001082 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001083 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +00001084 if (DBG) Log.d(TAG, "Stop service resolution");
1085 args = (ListenerArgs) msg.obj;
1086 clientInfo = mClients.get(args.connector);
1087 // If the binder death notification for a INsdManagerCallback was received
1088 // before any calls are received by NsdService, the clientInfo would be
1089 // cleared and cause NPE. Add a null check here to prevent this corner case.
1090 if (clientInfo == null) {
1091 Log.e(TAG, "Unknown connector in stop resolution");
1092 break;
1093 }
1094
Paul Hud44e1b72023-06-16 02:07:42 +00001095 final ClientRequest request =
1096 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001097 if (request == null) {
1098 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
1099 break;
1100 }
Paul Hud44e1b72023-06-16 02:07:42 +00001101 transactionId = request.mTransactionId;
Paul Hue4f5f252023-02-16 21:13:47 +08001102 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
1103 // point, so this needs to check the type of the original request to
1104 // unregister instead of looking at the flag value.
1105 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001106 stopDiscoveryManagerRequest(
1107 request, clientRequestId, transactionId, clientInfo);
Paul Hu60149052023-07-31 14:26:08 +08001108 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001109 clientInfo.log("Unregister the ResolutionListener " + transactionId);
Paul Hub58deb72022-12-26 09:24:42 +00001110 } else {
Paul Hud44e1b72023-06-16 02:07:42 +00001111 removeRequestMap(clientRequestId, transactionId, clientInfo);
1112 if (stopResolveService(transactionId)) {
Paul Hu60149052023-07-31 14:26:08 +08001113 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hue4f5f252023-02-16 21:13:47 +08001114 } else {
1115 clientInfo.onStopResolutionFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001116 clientRequestId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hue4f5f252023-02-16 21:13:47 +08001117 }
1118 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +00001119 }
Paul Hub58deb72022-12-26 09:24:42 +00001120 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001121 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001122 case NsdManager.REGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001123 if (DBG) Log.d(TAG, "Register a service callback");
1124 args = (ListenerArgs) msg.obj;
1125 clientInfo = mClients.get(args.connector);
1126 // If the binder death notification for a INsdManagerCallback was received
1127 // before any calls are received by NsdService, the clientInfo would be
1128 // cleared and cause NPE. Add a null check here to prevent this corner case.
1129 if (clientInfo == null) {
1130 Log.e(TAG, "Unknown connector in callback registration");
1131 break;
1132 }
1133
Paul Hu30bd70d2023-02-07 13:20:56 +00001134 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001135 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001136 final Pair<String, String> typeAndSubtype =
1137 parseTypeAndSubtype(info.getServiceType());
1138 final String serviceType = typeAndSubtype == null
1139 ? null : typeAndSubtype.first;
Paul Hu30bd70d2023-02-07 13:20:56 +00001140 if (serviceType == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001141 clientInfo.onServiceInfoCallbackRegistrationFailed(clientRequestId,
Paul Hu30bd70d2023-02-07 13:20:56 +00001142 NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +00001143 break;
1144 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001145 final String resolveServiceType = serviceType + ".local";
Paul Hu18aeccc2022-12-27 08:48:48 +00001146
Paul Hu30bd70d2023-02-07 13:20:56 +00001147 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001148 final MdnsListener listener = new ServiceInfoListener(clientRequestId,
1149 transactionId, info, resolveServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +00001150 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1151 .setNetwork(info.getNetwork())
1152 .setIsPassiveMode(true)
1153 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001154 .setRemoveExpiredService(true)
Paul Hu30bd70d2023-02-07 13:20:56 +00001155 .build();
1156 mMdnsDiscoveryManager.registerListener(
1157 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001158 storeDiscoveryManagerRequestMap(clientRequestId, transactionId, listener,
1159 clientInfo, info.getNetwork());
Paul Huddce5912023-08-01 10:26:49 +08001160 clientInfo.onServiceInfoCallbackRegistered(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00001161 clientInfo.log("Register a ServiceInfoListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001162 + " for service type:" + resolveServiceType);
Paul Hu18aeccc2022-12-27 08:48:48 +00001163 break;
Paul Hu30bd70d2023-02-07 13:20:56 +00001164 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001165 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001166 if (DBG) Log.d(TAG, "Unregister a service callback");
1167 args = (ListenerArgs) msg.obj;
1168 clientInfo = mClients.get(args.connector);
1169 // If the binder death notification for a INsdManagerCallback was received
1170 // before any calls are received by NsdService, the clientInfo would be
1171 // cleared and cause NPE. Add a null check here to prevent this corner case.
1172 if (clientInfo == null) {
1173 Log.e(TAG, "Unknown connector in callback unregistration");
1174 break;
1175 }
1176
Paul Hud44e1b72023-06-16 02:07:42 +00001177 final ClientRequest request =
1178 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001179 if (request == null) {
Paul Hu30bd70d2023-02-07 13:20:56 +00001180 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE_CALLBACK");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001181 break;
1182 }
Paul Hud44e1b72023-06-16 02:07:42 +00001183 transactionId = request.mTransactionId;
Paul Hu30bd70d2023-02-07 13:20:56 +00001184 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001185 stopDiscoveryManagerRequest(
1186 request, clientRequestId, transactionId, clientInfo);
Paul Huddce5912023-08-01 10:26:49 +08001187 clientInfo.onServiceInfoCallbackUnregistered(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001188 clientInfo.log("Unregister the ServiceInfoListener " + transactionId);
Paul Hu18aeccc2022-12-27 08:48:48 +00001189 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001190 loge("Unregister failed with non-DiscoveryManagerRequest.");
Paul Hu18aeccc2022-12-27 08:48:48 +00001191 }
Paul Hu18aeccc2022-12-27 08:48:48 +00001192 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001193 }
paulhu2b9ed952022-02-10 21:58:32 +08001194 case MDNS_SERVICE_EVENT:
1195 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +09001196 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001197 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001198 break;
Paul Hu019621e2023-01-13 23:26:49 +08001199 case MDNS_DISCOVERY_MANAGER_EVENT:
1200 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
1201 return NOT_HANDLED;
1202 }
1203 break;
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001204 case NsdManager.REGISTER_OFFLOAD_ENGINE:
1205 offloadEngineInfo = (OffloadEngineInfo) msg.obj;
1206 // TODO: Limits the number of registrations created by a given class.
1207 mOffloadEngines.register(offloadEngineInfo.mOffloadEngine,
1208 offloadEngineInfo);
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001209 sendAllOffloadServiceInfos(offloadEngineInfo);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001210 break;
1211 case NsdManager.UNREGISTER_OFFLOAD_ENGINE:
1212 mOffloadEngines.unregister((IOffloadEngine) msg.obj);
1213 break;
Irfan Sheriff75006652012-04-17 23:15:29 -07001214 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001215 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001216 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001217 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001218 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001219
Paul Hud44e1b72023-06-16 02:07:42 +00001220 private boolean handleMDnsServiceEvent(int code, int transactionId, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001221 NsdServiceInfo servInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001222 ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001223 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001224 Log.e(TAG, String.format(
1225 "transactionId %d for %d has no client mapping", transactionId, code));
Hugo Benichif0c84092017-04-05 14:43:29 +09001226 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001227 }
1228
1229 /* This goes in response as msg.arg2 */
Paul Hud44e1b72023-06-16 02:07:42 +00001230 int clientRequestId = clientInfo.getClientRequestId(transactionId);
1231 if (clientRequestId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -07001232 // This can happen because of race conditions. For example,
1233 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
1234 // and we may get in this situation.
Paul Hud44e1b72023-06-16 02:07:42 +00001235 Log.d(TAG, String.format("%d for transactionId %d that is no longer active",
1236 code, transactionId));
Hugo Benichif0c84092017-04-05 14:43:29 +09001237 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001238 }
Paul Hu812e9212023-06-20 06:24:53 +00001239 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1240 if (request == null) {
1241 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1242 return false;
1243 }
Hugo Benichi32be63d2017-04-05 14:06:11 +09001244 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00001245 Log.d(TAG, String.format(
1246 "MDns service event code:%d transactionId=%d", code, transactionId));
Hugo Benichi32be63d2017-04-05 14:06:11 +09001247 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001248 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +08001249 case IMDnsEventListener.SERVICE_FOUND: {
1250 final DiscoveryInfo info = (DiscoveryInfo) obj;
1251 final String name = info.serviceName;
1252 final String type = info.registrationType;
1253 servInfo = new NsdServiceInfo(name, type);
1254 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001255 if (foundNetId == 0L) {
1256 // Ignore services that do not have a Network: they are not usable
1257 // by apps, as they would need privileged permissions to use
1258 // interfaces that do not have an associated Network.
1259 break;
1260 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +09001261 if (foundNetId == INetd.DUMMY_NET_ID) {
1262 // Ignore services on the dummy0 interface: they are only seen when
1263 // discovering locally advertised services, and are not reachable
1264 // through that interface.
1265 break;
1266 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001267 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001268
1269 clientInfo.onServiceFound(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001270 break;
paulhu2b9ed952022-02-10 21:58:32 +08001271 }
1272 case IMDnsEventListener.SERVICE_LOST: {
1273 final DiscoveryInfo info = (DiscoveryInfo) obj;
1274 final String name = info.serviceName;
1275 final String type = info.registrationType;
1276 final int lostNetId = info.netId;
1277 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001278 // The network could be set to null (netId 0) if it was torn down when the
1279 // service is lost
1280 // TODO: avoid returning null in that case, possibly by remembering
1281 // found services on the same interface index and their network at the time
1282 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001283 clientInfo.onServiceLost(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001284 break;
paulhu2b9ed952022-02-10 21:58:32 +08001285 }
1286 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Paul Hu812e9212023-06-20 06:24:53 +00001287 clientInfo.onDiscoverServicesFailed(clientRequestId,
1288 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1289 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001290 break;
paulhu2b9ed952022-02-10 21:58:32 +08001291 case IMDnsEventListener.SERVICE_REGISTERED: {
1292 final RegistrationInfo info = (RegistrationInfo) obj;
1293 final String name = info.serviceName;
1294 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Paul Hu777ed052023-06-19 13:35:15 +00001295 clientInfo.onRegisterServiceSucceeded(clientRequestId, servInfo,
Paul Hu812e9212023-06-20 06:24:53 +00001296 transactionId,
1297 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001298 break;
paulhu2b9ed952022-02-10 21:58:32 +08001299 }
1300 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Paul Hu777ed052023-06-19 13:35:15 +00001301 clientInfo.onRegisterServiceFailed(clientRequestId,
1302 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001303 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001304 break;
paulhu2b9ed952022-02-10 21:58:32 +08001305 case IMDnsEventListener.SERVICE_RESOLVED: {
1306 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001307 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +08001308 final String fullName = info.serviceFullName;
1309 while (index < fullName.length() && fullName.charAt(index) != '.') {
1310 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001311 ++index;
1312 }
1313 ++index;
1314 }
paulhu2b9ed952022-02-10 21:58:32 +08001315 if (index >= fullName.length()) {
1316 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001317 break;
1318 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001319
paulhube186602022-04-12 07:18:23 +00001320 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001321 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001322 String type = rest.replace(".local.", "");
1323
Paul Hu30bd70d2023-02-07 13:20:56 +00001324 final NsdServiceInfo serviceInfo = clientInfo.mResolvedService;
Paul Hu18aeccc2022-12-27 08:48:48 +00001325 serviceInfo.setServiceName(name);
1326 serviceInfo.setServiceType(type);
1327 serviceInfo.setPort(info.port);
1328 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001329 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001330
Paul Hud44e1b72023-06-16 02:07:42 +00001331 stopResolveService(transactionId);
1332 removeRequestMap(clientRequestId, transactionId, clientInfo);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001333
Paul Hud44e1b72023-06-16 02:07:42 +00001334 final int transactionId2 = getUniqueId();
1335 if (getAddrInfo(transactionId2, info.hostname, info.interfaceIdx)) {
1336 storeLegacyRequestMap(clientRequestId, transactionId2, clientInfo,
Paul Hua6bc4632023-06-26 01:18:29 +00001337 NsdManager.RESOLVE_SERVICE, request.mStartTimeMs);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001338 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001339 clientInfo.onResolveServiceFailed(clientRequestId,
1340 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1341 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001342 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001343 }
1344 break;
paulhu2b9ed952022-02-10 21:58:32 +08001345 }
1346 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001347 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001348 stopResolveService(transactionId);
1349 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001350 clientInfo.onResolveServiceFailed(clientRequestId,
1351 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1352 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001353 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001354 break;
paulhu2b9ed952022-02-10 21:58:32 +08001355 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001356 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001357 stopGetAddrInfo(transactionId);
1358 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001359 clientInfo.onResolveServiceFailed(clientRequestId,
1360 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1361 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001362 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001363 break;
paulhu2b9ed952022-02-10 21:58:32 +08001364 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001365 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001366 final GetAddressInfo info = (GetAddressInfo) obj;
1367 final String address = info.address;
1368 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001369 InetAddress serviceHost = null;
1370 try {
paulhu2b9ed952022-02-10 21:58:32 +08001371 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001372 } catch (UnknownHostException e) {
1373 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1374 }
1375
1376 // If the resolved service is on an interface without a network, consider it
1377 // as a failure: it would not be usable by apps as they would need
1378 // privileged permissions.
Paul Hu30bd70d2023-02-07 13:20:56 +00001379 if (netId != NETID_UNSET && serviceHost != null) {
1380 clientInfo.mResolvedService.setHost(serviceHost);
1381 setServiceNetworkForCallback(clientInfo.mResolvedService,
1382 netId, info.interfaceIdx);
1383 clientInfo.onResolveServiceSucceeded(
Paul Hua6bc4632023-06-26 01:18:29 +00001384 clientRequestId, clientInfo.mResolvedService, request);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001385 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001386 clientInfo.onResolveServiceFailed(clientRequestId,
1387 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1388 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001389 }
Paul Hud44e1b72023-06-16 02:07:42 +00001390 stopGetAddrInfo(transactionId);
1391 removeRequestMap(clientRequestId, transactionId, clientInfo);
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 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001395 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001396 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001397 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001398 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001399 }
Paul Hu019621e2023-01-13 23:26:49 +08001400
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001401 @Nullable
1402 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(
1403 final MdnsEvent event, int code) {
Paul Hu019621e2023-01-13 23:26:49 +08001404 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001405 final String[] typeArray = serviceInfo.getServiceType();
1406 final String joinedType;
1407 if (typeArray.length == 0
1408 || !typeArray[typeArray.length - 1].equals(LOCAL_DOMAIN_NAME)) {
1409 Log.wtf(TAG, "MdnsServiceInfo type does not end in .local: "
1410 + Arrays.toString(typeArray));
1411 return null;
1412 } else {
1413 joinedType = TextUtils.join(".",
1414 Arrays.copyOfRange(typeArray, 0, typeArray.length - 1));
1415 }
1416 final String serviceType;
1417 switch (code) {
1418 case NsdManager.SERVICE_FOUND:
1419 case NsdManager.SERVICE_LOST:
1420 // For consistency with historical behavior, discovered service types have
1421 // a dot at the end.
1422 serviceType = joinedType + ".";
1423 break;
1424 case RESOLVE_SERVICE_SUCCEEDED:
1425 // For consistency with historical behavior, resolved service types have
1426 // a dot at the beginning.
1427 serviceType = "." + joinedType;
1428 break;
1429 default:
1430 serviceType = joinedType;
1431 break;
1432 }
Paul Hu019621e2023-01-13 23:26:49 +08001433 final String serviceName = serviceInfo.getServiceInstanceName();
1434 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1435 final Network network = serviceInfo.getNetwork();
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001436 // In MdnsDiscoveryManagerEvent, the Network can be null which means it is a
1437 // network for Tethering interface. In other words, the network == null means the
1438 // network has netId = INetd.LOCAL_NET_ID.
Paul Hu019621e2023-01-13 23:26:49 +08001439 setServiceNetworkForCallback(
1440 servInfo,
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001441 network == null ? INetd.LOCAL_NET_ID : network.netId,
Paul Hu019621e2023-01-13 23:26:49 +08001442 serviceInfo.getInterfaceIndex());
1443 return servInfo;
1444 }
1445
1446 private boolean handleMdnsDiscoveryManagerEvent(
1447 int transactionId, int code, Object obj) {
Paul Hud44e1b72023-06-16 02:07:42 +00001448 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Paul Hu019621e2023-01-13 23:26:49 +08001449 if (clientInfo == null) {
1450 Log.e(TAG, String.format(
1451 "id %d for %d has no client mapping", transactionId, code));
1452 return false;
1453 }
1454
1455 final MdnsEvent event = (MdnsEvent) obj;
Paul Hud44e1b72023-06-16 02:07:42 +00001456 final int clientRequestId = event.mClientRequestId;
Paul Hubad6fe92023-07-24 21:25:22 +08001457 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1458 if (request == null) {
1459 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1460 return false;
1461 }
1462
1463 // Deal with the discovery sent callback
1464 if (code == DISCOVERY_QUERY_SENT_CALLBACK) {
1465 request.onQuerySent();
1466 return true;
1467 }
1468
1469 // Deal with other callbacks.
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001470 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event, code);
1471 // Errors are already logged if null
1472 if (info == null) return false;
Paul Hu83ec7f42023-06-07 18:04:09 +08001473 mServiceLogs.log(String.format(
1474 "MdnsDiscoveryManager event code=%s transactionId=%d",
1475 NsdManager.nameOf(code), transactionId));
Paul Hu019621e2023-01-13 23:26:49 +08001476 switch (code) {
1477 case NsdManager.SERVICE_FOUND:
Paul Hu812e9212023-06-20 06:24:53 +00001478 clientInfo.onServiceFound(clientRequestId, info, request);
Paul Hu319751a2023-01-13 23:56:34 +08001479 break;
1480 case NsdManager.SERVICE_LOST:
Paul Hu812e9212023-06-20 06:24:53 +00001481 clientInfo.onServiceLost(clientRequestId, info, request);
Paul Hu019621e2023-01-13 23:26:49 +08001482 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001483 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
1484 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Paul Hu75069ed2023-01-14 00:31:09 +08001485 info.setPort(serviceInfo.getPort());
1486
1487 Map<String, String> attrs = serviceInfo.getAttributes();
1488 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1489 final String key = kv.getKey();
1490 try {
1491 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1492 } catch (IllegalArgumentException e) {
1493 Log.e(TAG, "Invalid attribute", e);
1494 }
1495 }
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001496 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu2b865912023-03-06 14:27:53 +08001497 if (addresses.size() != 0) {
1498 info.setHostAddresses(addresses);
Paul Hua6bc4632023-06-26 01:18:29 +00001499 request.setServiceFromCache(event.mIsServiceFromCache);
1500 clientInfo.onResolveServiceSucceeded(clientRequestId, info, request);
Paul Hu2b865912023-03-06 14:27:53 +08001501 } else {
1502 // No address. Notify resolution failure.
Paul Hua6bc4632023-06-26 01:18:29 +00001503 clientInfo.onResolveServiceFailed(clientRequestId,
1504 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1505 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu75069ed2023-01-14 00:31:09 +08001506 }
1507
1508 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001509 if (!(request instanceof DiscoveryManagerRequest)) {
1510 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1511 break;
1512 }
Paul Hud44e1b72023-06-16 02:07:42 +00001513 stopDiscoveryManagerRequest(
1514 request, clientRequestId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001515 break;
1516 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001517 case NsdManager.SERVICE_UPDATED: {
1518 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1519 info.setPort(serviceInfo.getPort());
1520
1521 Map<String, String> attrs = serviceInfo.getAttributes();
1522 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1523 final String key = kv.getKey();
1524 try {
1525 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1526 } catch (IllegalArgumentException e) {
1527 Log.e(TAG, "Invalid attribute", e);
1528 }
1529 }
1530
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001531 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001532 info.setHostAddresses(addresses);
Paul Huddce5912023-08-01 10:26:49 +08001533 clientInfo.onServiceUpdated(clientRequestId, info, request);
1534 // Set the ServiceFromCache flag only if the service is actually being
1535 // retrieved from the cache. This flag should not be overridden by later
1536 // service updates, which may not be cached.
1537 if (event.mIsServiceFromCache) {
1538 request.setServiceFromCache(true);
1539 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001540 break;
1541 }
1542 case NsdManager.SERVICE_UPDATED_LOST:
Paul Huddce5912023-08-01 10:26:49 +08001543 clientInfo.onServiceUpdatedLost(clientRequestId, request);
Paul Hu30bd70d2023-02-07 13:20:56 +00001544 break;
Paul Hu019621e2023-01-13 23:26:49 +08001545 default:
1546 return false;
1547 }
1548 return true;
1549 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001550 }
1551 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001552
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001553 @NonNull
1554 private static List<InetAddress> getInetAddresses(@NonNull MdnsServiceInfo serviceInfo) {
1555 final List<String> v4Addrs = serviceInfo.getIpv4Addresses();
1556 final List<String> v6Addrs = serviceInfo.getIpv6Addresses();
1557 final List<InetAddress> addresses = new ArrayList<>(v4Addrs.size() + v6Addrs.size());
1558 for (String ipv4Address : v4Addrs) {
1559 try {
1560 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1561 } catch (IllegalArgumentException e) {
1562 Log.wtf(TAG, "Invalid ipv4 address", e);
1563 }
1564 }
1565 for (String ipv6Address : v6Addrs) {
1566 try {
Yuyang Huanga6a6ff92023-04-24 13:33:34 +09001567 final Inet6Address addr = (Inet6Address) InetAddresses.parseNumericAddress(
1568 ipv6Address);
1569 addresses.add(InetAddressUtils.withScopeId(addr, serviceInfo.getInterfaceIndex()));
1570 } catch (IllegalArgumentException e) {
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001571 Log.wtf(TAG, "Invalid ipv6 address", e);
1572 }
1573 }
1574 return addresses;
1575 }
1576
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001577 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1578 switch (netId) {
1579 case NETID_UNSET:
1580 info.setNetwork(null);
1581 break;
1582 case INetd.LOCAL_NET_ID:
1583 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1584 // visible / usable for apps, so do not return it. Store the interface
1585 // index instead, so at least if the client tries to resolve the service
1586 // with that NsdServiceInfo, it will be done on the same interface.
1587 // If they recreate the NsdServiceInfo themselves, resolution would be
1588 // done on all interfaces as before T, which should also work.
1589 info.setNetwork(null);
1590 info.setInterfaceIndex(ifaceIdx);
1591 break;
1592 default:
1593 info.setNetwork(new Network(netId));
1594 }
1595 }
1596
paulhube186602022-04-12 07:18:23 +00001597 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1598 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1599 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1600 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1601 private String unescape(String s) {
1602 StringBuilder sb = new StringBuilder(s.length());
1603 for (int i = 0; i < s.length(); ++i) {
1604 char c = s.charAt(i);
1605 if (c == '\\') {
1606 if (++i >= s.length()) {
1607 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1608 break;
1609 }
1610 c = s.charAt(i);
1611 if (c != '.' && c != '\\') {
1612 if (i + 2 >= s.length()) {
1613 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1614 break;
1615 }
1616 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1617 + (s.charAt(i + 2) - '0'));
1618 i += 2;
1619 }
1620 }
1621 sb.append(c);
1622 }
1623 return sb.toString();
1624 }
1625
Paul Hu7445e3d2023-03-03 15:14:00 +08001626 /**
1627 * Check the given service type is valid and construct it to a service type
1628 * which can use for discovery / resolution service.
1629 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001630 * <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 +08001631 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1632 * underscore; they are alphanumerical characters or dashes or underscore, except the
1633 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1634 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001635 * <p>The subtype may also be specified with a comma after the service type, for example
1636 * _type._tcp,_subtype.
1637 *
Paul Hu7445e3d2023-03-03 15:14:00 +08001638 * @param serviceType the request service type for discovery / resolution service
1639 * @return constructed service type or null if the given service type is invalid.
1640 */
1641 @Nullable
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001642 public static Pair<String, String> parseTypeAndSubtype(String serviceType) {
Paul Hu7445e3d2023-03-03 15:14:00 +08001643 if (TextUtils.isEmpty(serviceType)) return null;
1644
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001645 final String typeOrSubtypePattern = "_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]";
Paul Hu7445e3d2023-03-03 15:14:00 +08001646 final Pattern serviceTypePattern = Pattern.compile(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001647 // Optional leading subtype (_subtype._type._tcp)
1648 // (?: xxx) is a non-capturing parenthesis, don't capture the dot
1649 "^(?:(" + typeOrSubtypePattern + ")\\.)?"
1650 // Actual type (_type._tcp.local)
1651 + "(" + typeOrSubtypePattern + "\\._(?:tcp|udp))"
Paul Hu7445e3d2023-03-03 15:14:00 +08001652 // Drop '.' at the end of service type that is compatible with old backend.
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001653 // e.g. allow "_type._tcp.local."
1654 + "\\.?"
1655 // Optional subtype after comma, for "_type._tcp,_subtype" format
1656 + "(?:,(" + typeOrSubtypePattern + "))?"
1657 + "$");
Paul Hu7445e3d2023-03-03 15:14:00 +08001658 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1659 if (!matcher.matches()) return null;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001660 // Use the subtype either at the beginning or after the comma
1661 final String subtype = matcher.group(1) != null ? matcher.group(1) : matcher.group(3);
1662 return new Pair<>(matcher.group(2), subtype);
Paul Hu7445e3d2023-03-03 15:14:00 +08001663 }
1664
Hugo Benichi803a2f02017-04-24 11:35:06 +09001665 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001666 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001667 this(ctx, handler, cleanupDelayMs, new Dependencies());
1668 }
1669
1670 @VisibleForTesting
1671 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001672 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001673 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001674 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001675 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001676 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1677 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001678 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001679
Paul Hu14667de2023-04-17 22:42:47 +08001680 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper(),
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001681 LOGGER.forSubComponent("MdnsSocketProvider"), new SocketRequestMonitor());
Yuyang Huang700778b2023-03-08 16:17:05 +09001682 // Netlink monitor starts on boot, and intentionally never stopped, to ensure that all
1683 // address events are received.
1684 handler.post(mMdnsSocketProvider::startNetLinkMonitor);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001685
1686 // NsdService is started after ActivityManager (startOtherServices in SystemServer, vs.
1687 // startBootstrapServices).
1688 mRunningAppActiveImportanceCutoff = mDeps.getDeviceConfigInt(
1689 MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF,
1690 DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF);
1691 final ActivityManager am = ctx.getSystemService(ActivityManager.class);
1692 am.addOnUidImportanceListener(new UidImportanceListener(handler),
1693 mRunningAppActiveImportanceCutoff);
1694
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001695 mMdnsSocketClient =
Yuyang Huang7ddf2932023-08-01 18:16:30 +09001696 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider,
1697 LOGGER.forSubComponent("MdnsMultinetworkSocketClient"));
Paul Hu14667de2023-04-17 22:42:47 +08001698 mMdnsDiscoveryManager = deps.makeMdnsDiscoveryManager(new ExecutorProvider(),
Yuyang Huang243d1a52023-05-23 17:26:52 +09001699 mMdnsSocketClient, LOGGER.forSubComponent("MdnsDiscoveryManager"));
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001700 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
Yuyang Huangb96a0712023-09-07 15:13:15 +09001701 MdnsFeatureFlags flags = new MdnsFeatureFlags.Builder().setIsMdnsOffloadFeatureEnabled(
1702 mDeps.isTetheringFeatureNotChickenedOut(
1703 MdnsFeatureFlags.NSD_FORCE_DISABLE_MDNS_OFFLOAD)).build();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001704 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
Yuyang Huangb96a0712023-09-07 15:13:15 +09001705 new AdvertiserCallback(), LOGGER.forSubComponent("MdnsAdvertiser"), flags);
Paul Hu777ed052023-06-19 13:35:15 +00001706 mClock = deps.makeClock();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001707 }
1708
1709 /**
1710 * Dependencies of NsdService, for injection in tests.
1711 */
1712 @VisibleForTesting
1713 public static class Dependencies {
1714 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001715 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001716 *
1717 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001718 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001719 */
1720 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001721 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001722 MDNS_DISCOVERY_MANAGER_VERSION);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001723 }
1724
1725 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001726 * Check whether the MdnsAdvertiser feature is enabled.
1727 *
1728 * @param context The global context information about an app environment.
1729 * @return true if the MdnsAdvertiser feature is enabled.
1730 */
1731 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001732 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001733 MDNS_ADVERTISER_VERSION);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001734 }
1735
1736 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001737 * Get the type allowlist flag value.
1738 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1739 */
1740 @Nullable
1741 public String getTypeAllowlistFlags() {
1742 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1743 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1744 }
1745
1746 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001747 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001748 */
1749 public boolean isFeatureEnabled(Context context, String feature) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001750 return DeviceConfigUtils.isTetheringFeatureEnabled(context, feature);
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001751 }
1752
1753 /**
Yuyang Huangb96a0712023-09-07 15:13:15 +09001754 * @see DeviceConfigUtils#isTetheringFeatureNotChickenedOut
1755 */
1756 public boolean isTetheringFeatureNotChickenedOut(String feature) {
1757 return DeviceConfigUtils.isTetheringFeatureNotChickenedOut(feature);
1758 }
1759
1760 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001761 * @see MdnsDiscoveryManager
1762 */
1763 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
Paul Hu14667de2023-04-17 22:42:47 +08001764 @NonNull ExecutorProvider executorProvider,
Yuyang Huang243d1a52023-05-23 17:26:52 +09001765 @NonNull MdnsMultinetworkSocketClient socketClient, @NonNull SharedLog sharedLog) {
1766 return new MdnsDiscoveryManager(executorProvider, socketClient, sharedLog);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001767 }
1768
1769 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001770 * @see MdnsAdvertiser
1771 */
1772 public MdnsAdvertiser makeMdnsAdvertiser(
1773 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
Yuyang Huangb96a0712023-09-07 15:13:15 +09001774 @NonNull MdnsAdvertiser.AdvertiserCallback cb, @NonNull SharedLog sharedLog,
1775 MdnsFeatureFlags featureFlags) {
1776 return new MdnsAdvertiser(looper, socketProvider, cb, sharedLog, featureFlags);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001777 }
1778
1779 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001780 * @see MdnsSocketProvider
1781 */
Paul Hu14667de2023-04-17 22:42:47 +08001782 public MdnsSocketProvider makeMdnsSocketProvider(@NonNull Context context,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001783 @NonNull Looper looper, @NonNull SharedLog sharedLog,
1784 @NonNull MdnsSocketProvider.SocketRequestMonitor socketCreationCallback) {
1785 return new MdnsSocketProvider(context, looper, sharedLog, socketCreationCallback);
1786 }
1787
1788 /**
1789 * @see DeviceConfig#getInt(String, String, int)
1790 */
1791 public int getDeviceConfigInt(@NonNull String config, int defaultValue) {
1792 return DeviceConfig.getInt(NAMESPACE_TETHERING, config, defaultValue);
1793 }
1794
1795 /**
1796 * @see Binder#getCallingUid()
1797 */
1798 public int getCallingUid() {
1799 return Binder.getCallingUid();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001800 }
Paul Hu777ed052023-06-19 13:35:15 +00001801
1802 /**
1803 * @see NetworkNsdReportedMetrics
1804 */
1805 public NetworkNsdReportedMetrics makeNetworkNsdReportedMetrics(
1806 boolean isLegacy, int clientId) {
1807 return new NetworkNsdReportedMetrics(isLegacy, clientId);
1808 }
1809
1810 /**
1811 * @see MdnsUtils.Clock
1812 */
1813 public Clock makeClock() {
1814 return new Clock();
1815 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001816 }
1817
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001818 /**
1819 * Return whether a type is allowlisted to use the Java backend.
1820 * @param type The service type
1821 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1822 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1823 */
1824 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1825 @NonNull String flagPrefix) {
1826 if (type == null) return false;
1827 final String typesConfig = mDeps.getTypeAllowlistFlags();
1828 if (TextUtils.isEmpty(typesConfig)) return false;
1829
1830 final String mappingPrefix = type + ":";
1831 String mappedFlag = null;
1832 for (String mapping : TextUtils.split(typesConfig, ",")) {
1833 if (mapping.startsWith(mappingPrefix)) {
1834 mappedFlag = mapping.substring(mappingPrefix.length());
1835 break;
1836 }
1837 }
1838
1839 if (mappedFlag == null) return false;
1840
1841 return mDeps.isFeatureEnabled(mContext,
1842 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1843 }
1844
1845 private boolean useDiscoveryManagerForType(@Nullable String type) {
1846 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1847 }
1848
1849 private boolean useAdvertiserForType(@Nullable String type) {
1850 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1851 }
1852
paulhu1b35e822022-04-08 14:48:41 +08001853 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001854 HandlerThread thread = new HandlerThread(TAG);
1855 thread.start();
1856 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001857 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001858 return service;
1859 }
1860
paulhu2b9ed952022-02-10 21:58:32 +08001861 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1862 private final StateMachine mStateMachine;
1863
1864 MDnsEventCallback(StateMachine sm) {
1865 mStateMachine = sm;
1866 }
1867
1868 @Override
1869 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1870 mStateMachine.sendMessage(
1871 MDNS_SERVICE_EVENT, status.result, status.id, status);
1872 }
1873
1874 @Override
1875 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1876 mStateMachine.sendMessage(
1877 MDNS_SERVICE_EVENT, status.result, status.id, status);
1878 }
1879
1880 @Override
1881 public void onServiceResolutionStatus(final ResolutionInfo status) {
1882 mStateMachine.sendMessage(
1883 MDNS_SERVICE_EVENT, status.result, status.id, status);
1884 }
1885
1886 @Override
1887 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1888 mStateMachine.sendMessage(
1889 MDNS_SERVICE_EVENT, status.result, status.id, status);
1890 }
1891
1892 @Override
1893 public int getInterfaceVersion() throws RemoteException {
1894 return this.VERSION;
1895 }
1896
1897 @Override
1898 public String getInterfaceHash() throws RemoteException {
1899 return this.HASH;
1900 }
1901 }
1902
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001903 private void sendAllOffloadServiceInfos(@NonNull OffloadEngineInfo offloadEngineInfo) {
1904 final String targetInterface = offloadEngineInfo.mInterfaceName;
1905 final IOffloadEngine offloadEngine = offloadEngineInfo.mOffloadEngine;
1906 final List<MdnsAdvertiser.OffloadServiceInfoWrapper> offloadWrappers =
1907 mAdvertiser.getAllInterfaceOffloadServiceInfos(targetInterface);
1908 for (MdnsAdvertiser.OffloadServiceInfoWrapper wrapper : offloadWrappers) {
1909 try {
1910 offloadEngine.onOffloadServiceUpdated(wrapper.mOffloadServiceInfo);
1911 } catch (RemoteException e) {
1912 // Can happen in regular cases, do not log a stacktrace
1913 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
1914 }
1915 }
1916 }
1917
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001918 private void sendOffloadServiceInfosUpdate(@NonNull String targetInterfaceName,
1919 @NonNull OffloadServiceInfo offloadServiceInfo, boolean isRemove) {
1920 final int count = mOffloadEngines.beginBroadcast();
1921 try {
1922 for (int i = 0; i < count; i++) {
1923 final OffloadEngineInfo offloadEngineInfo =
1924 (OffloadEngineInfo) mOffloadEngines.getBroadcastCookie(i);
1925 final String interfaceName = offloadEngineInfo.mInterfaceName;
1926 if (!targetInterfaceName.equals(interfaceName)
1927 || ((offloadEngineInfo.mOffloadType
1928 & offloadServiceInfo.getOffloadType()) == 0)) {
1929 continue;
1930 }
1931 try {
1932 if (isRemove) {
1933 mOffloadEngines.getBroadcastItem(i).onOffloadServiceRemoved(
1934 offloadServiceInfo);
1935 } else {
1936 mOffloadEngines.getBroadcastItem(i).onOffloadServiceUpdated(
1937 offloadServiceInfo);
1938 }
1939 } catch (RemoteException e) {
1940 // Can happen in regular cases, do not log a stacktrace
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001941 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001942 }
1943 }
1944 } finally {
1945 mOffloadEngines.finishBroadcast();
1946 }
1947 }
1948
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001949 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001950 // TODO: add a callback to notify when a service is being added on each interface (as soon
1951 // as probing starts), and call mOffloadCallbacks. This callback is for
1952 // OFFLOAD_CAPABILITY_FILTER_REPLIES offload type.
1953
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001954 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001955 public void onRegisterServiceSucceeded(int transactionId, NsdServiceInfo registeredInfo) {
1956 mServiceLogs.log("onRegisterServiceSucceeded: transactionId " + transactionId);
1957 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001958 if (clientInfo == null) return;
1959
Paul Hud44e1b72023-06-16 02:07:42 +00001960 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1961 if (clientRequestId < 0) return;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001962
1963 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1964 // historical behavior.
1965 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
Paul Hu777ed052023-06-19 13:35:15 +00001966 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu812e9212023-06-20 06:24:53 +00001967 clientInfo.onRegisterServiceSucceeded(clientRequestId, cbInfo, transactionId,
1968 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001969 }
1970
1971 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001972 public void onRegisterServiceFailed(int transactionId, int errorCode) {
1973 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001974 if (clientInfo == null) return;
1975
Paul Hud44e1b72023-06-16 02:07:42 +00001976 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1977 if (clientRequestId < 0) return;
Paul Hu777ed052023-06-19 13:35:15 +00001978 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1979 clientInfo.onRegisterServiceFailed(clientRequestId, errorCode, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001980 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001981 }
1982
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001983 @Override
1984 public void onOffloadStartOrUpdate(@NonNull String interfaceName,
1985 @NonNull OffloadServiceInfo offloadServiceInfo) {
1986 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, false /* isRemove */);
1987 }
1988
1989 @Override
1990 public void onOffloadStop(@NonNull String interfaceName,
1991 @NonNull OffloadServiceInfo offloadServiceInfo) {
1992 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, true /* isRemove */);
1993 }
1994
Paul Hud44e1b72023-06-16 02:07:42 +00001995 private ClientInfo getClientInfoOrLog(int transactionId) {
1996 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001997 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001998 Log.e(TAG, String.format("Callback for service %d has no client", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001999 }
2000 return clientInfo;
2001 }
2002
Paul Hud44e1b72023-06-16 02:07:42 +00002003 private int getClientRequestIdOrLog(@NonNull ClientInfo info, int transactionId) {
2004 final int clientRequestId = info.getClientRequestId(transactionId);
2005 if (clientRequestId < 0) {
2006 Log.e(TAG, String.format(
2007 "Client request ID not found for service %d", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002008 }
Paul Hud44e1b72023-06-16 02:07:42 +00002009 return clientRequestId;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002010 }
2011 }
2012
Paul Hu2e0a88c2023-03-09 16:05:01 +08002013 private static class ConnectorArgs {
2014 @NonNull public final NsdServiceConnector connector;
2015 @NonNull public final INsdManagerCallback callback;
2016 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002017 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002018
2019 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00002020 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08002021 this.connector = connector;
2022 this.callback = callback;
2023 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002024 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002025 }
2026 }
2027
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002028 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08002029 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09002030 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu101dbf52023-08-09 16:05:20 +08002031 final int uid = mDeps.getCallingUid();
2032 if (cb == null) {
2033 throw new IllegalArgumentException("Unknown client callback from uid=" + uid);
2034 }
Paul Hu2e0a88c2023-03-09 16:05:01 +08002035 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002036 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00002037 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
Paul Hu101dbf52023-08-09 16:05:20 +08002038 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend, uid)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002039 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07002040 }
2041
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002042 private static class ListenerArgs {
2043 public final NsdServiceConnector connector;
2044 public final NsdServiceInfo serviceInfo;
2045 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
2046 this.connector = connector;
2047 this.serviceInfo = serviceInfo;
2048 }
2049 }
2050
2051 private class NsdServiceConnector extends INsdServiceConnector.Stub
2052 implements IBinder.DeathRecipient {
2053 @Override
2054 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
2055 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2056 NsdManager.REGISTER_SERVICE, 0, listenerKey,
2057 new ListenerArgs(this, serviceInfo)));
2058 }
2059
2060 @Override
2061 public void unregisterService(int listenerKey) {
2062 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2063 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
2064 new ListenerArgs(this, null)));
2065 }
2066
2067 @Override
2068 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
2069 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2070 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
2071 new ListenerArgs(this, serviceInfo)));
2072 }
2073
2074 @Override
2075 public void stopDiscovery(int listenerKey) {
2076 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2077 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
2078 }
2079
2080 @Override
2081 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
2082 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2083 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
2084 new ListenerArgs(this, serviceInfo)));
2085 }
2086
2087 @Override
Paul Hub58deb72022-12-26 09:24:42 +00002088 public void stopResolution(int listenerKey) {
2089 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2090 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
2091 }
2092
2093 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00002094 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
2095 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2096 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
2097 new ListenerArgs(this, serviceInfo)));
2098 }
2099
2100 @Override
2101 public void unregisterServiceInfoCallback(int listenerKey) {
2102 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2103 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
2104 new ListenerArgs(this, null)));
2105 }
2106
2107 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002108 public void startDaemon() {
2109 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2110 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
2111 }
2112
2113 @Override
2114 public void binderDied() {
2115 mNsdStateMachine.sendMessage(
2116 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002117
2118 }
2119
2120 @Override
2121 public void registerOffloadEngine(String ifaceName, IOffloadEngine cb,
2122 @OffloadEngine.OffloadCapability long offloadCapabilities,
2123 @OffloadEngine.OffloadType long offloadTypes) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002124 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002125 Objects.requireNonNull(ifaceName);
2126 Objects.requireNonNull(cb);
2127 mNsdStateMachine.sendMessage(
2128 mNsdStateMachine.obtainMessage(NsdManager.REGISTER_OFFLOAD_ENGINE,
2129 new OffloadEngineInfo(cb, ifaceName, offloadCapabilities,
2130 offloadTypes)));
2131 }
2132
2133 @Override
2134 public void unregisterOffloadEngine(IOffloadEngine cb) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002135 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002136 Objects.requireNonNull(cb);
2137 mNsdStateMachine.sendMessage(
2138 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_OFFLOAD_ENGINE, cb));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002139 }
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002140
2141 private static void checkOffloadEnginePermission(Context context) {
2142 if (!SdkLevel.isAtLeastT()) {
2143 throw new SecurityException("API is not available in before API level 33");
2144 }
2145 // REGISTER_NSD_OFFLOAD_ENGINE was only added to the SDK in V, but may
2146 // be back ported to older builds: accept it as long as it's signature-protected
2147 if (PermissionUtils.checkAnyPermissionOf(context, REGISTER_NSD_OFFLOAD_ENGINE)
2148 && (SdkLevel.isAtLeastV() || PermissionUtils.isSystemSignaturePermission(
2149 context, REGISTER_NSD_OFFLOAD_ENGINE))) {
2150 return;
2151 }
2152 if (PermissionUtils.checkAnyPermissionOf(context, NETWORK_STACK,
2153 PERMISSION_MAINLINE_NETWORK_STACK, NETWORK_SETTINGS)) {
2154 return;
2155 }
2156 throw new SecurityException("Requires one of the following permissions: "
2157 + String.join(", ", List.of(REGISTER_NSD_OFFLOAD_ENGINE, NETWORK_STACK,
2158 PERMISSION_MAINLINE_NETWORK_STACK, NETWORK_SETTINGS)) + ".");
2159 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002160 }
2161
Hugo Benichi912db992017-04-24 16:41:03 +09002162 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07002163 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07002164 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09002165 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
2166 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07002167 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07002168 }
2169
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002170 private int getUniqueId() {
2171 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
2172 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002173 }
2174
Paul Hud44e1b72023-06-16 02:07:42 +00002175 private boolean registerService(int transactionId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09002176 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002177 Log.d(TAG, "registerService: " + transactionId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002178 }
Hugo Benichi6d706442017-04-24 16:19:58 +09002179 String name = service.getServiceName();
2180 String type = service.getServiceType();
2181 int port = service.getPort();
2182 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002183 final int registerInterface = getNetworkInterfaceIndex(service);
2184 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08002185 Log.e(TAG, "Interface to register service on not found");
2186 return false;
2187 }
Paul Hud44e1b72023-06-16 02:07:42 +00002188 return mMDnsManager.registerService(
2189 transactionId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002190 }
2191
Paul Hud44e1b72023-06-16 02:07:42 +00002192 private boolean unregisterService(int transactionId) {
2193 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002194 }
2195
Paul Hud44e1b72023-06-16 02:07:42 +00002196 private boolean discoverServices(int transactionId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08002197 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002198 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
2199 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002200 Log.e(TAG, "Interface to discover service on not found");
2201 return false;
2202 }
Paul Hud44e1b72023-06-16 02:07:42 +00002203 return mMDnsManager.discover(transactionId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002204 }
2205
Paul Hud44e1b72023-06-16 02:07:42 +00002206 private boolean stopServiceDiscovery(int transactionId) {
2207 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002208 }
2209
Paul Hud44e1b72023-06-16 02:07:42 +00002210 private boolean resolveService(int transactionId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002211 final String name = service.getServiceName();
2212 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002213 final int resolveInterface = getNetworkInterfaceIndex(service);
2214 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002215 Log.e(TAG, "Interface to resolve service on not found");
2216 return false;
2217 }
Paul Hud44e1b72023-06-16 02:07:42 +00002218 return mMDnsManager.resolve(transactionId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002219 }
2220
2221 /**
2222 * Guess the interface to use to resolve or discover a service on a specific network.
2223 *
2224 * This is an imperfect guess, as for example the network may be gone or not yet fully
2225 * registered. This is fine as failing is correct if the network is gone, and a client
2226 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
2227 * this is to support the legacy mdnsresponder implementation, which historically resolved
2228 * services on an unspecified network.
2229 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002230 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
2231 final Network network = serviceInfo.getNetwork();
2232 if (network == null) {
2233 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
2234 // provided by NsdService from discovery results, and the service was found on an
2235 // interface that has no app-usable Network).
2236 if (serviceInfo.getInterfaceIndex() != 0) {
2237 return serviceInfo.getInterfaceIndex();
2238 }
2239 return IFACE_IDX_ANY;
2240 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002241
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002242 String interfaceName = getNetworkInterfaceName(network);
2243 if (interfaceName == null) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002244 return IFACE_IDX_ANY;
2245 }
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002246 return getNetworkInterfaceIndexByName(interfaceName);
2247 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002248
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002249 private String getNetworkInterfaceName(@Nullable Network network) {
2250 if (network == null) {
2251 return null;
2252 }
2253 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
2254 if (cm == null) {
2255 Log.wtf(TAG, "No ConnectivityManager");
2256 return null;
2257 }
2258 final LinkProperties lp = cm.getLinkProperties(network);
2259 if (lp == null) {
2260 return null;
2261 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002262 // Only resolve on non-stacked interfaces
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002263 return lp.getInterfaceName();
2264 }
2265
2266 private int getNetworkInterfaceIndexByName(final String ifaceName) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002267 final NetworkInterface iface;
2268 try {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002269 iface = NetworkInterface.getByName(ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002270 } catch (SocketException e) {
2271 Log.e(TAG, "Error querying interface", e);
2272 return IFACE_IDX_ANY;
2273 }
2274
2275 if (iface == null) {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002276 Log.e(TAG, "Interface not found: " + ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002277 return IFACE_IDX_ANY;
2278 }
2279
2280 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002281 }
2282
Paul Hud44e1b72023-06-16 02:07:42 +00002283 private boolean stopResolveService(int transactionId) {
2284 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002285 }
2286
Paul Hud44e1b72023-06-16 02:07:42 +00002287 private boolean getAddrInfo(int transactionId, String hostname, int interfaceIdx) {
2288 return mMDnsManager.getServiceAddress(transactionId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002289 }
2290
Paul Hud44e1b72023-06-16 02:07:42 +00002291 private boolean stopGetAddrInfo(int transactionId) {
2292 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002293 }
2294
2295 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00002296 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2297 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002298
Paul Hub2e67d32023-04-18 05:50:14 +00002299 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2300 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07002301 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00002302
2303 // Dump service and clients logs
2304 pw.println();
Paul Hu14667de2023-04-17 22:42:47 +08002305 pw.println("Logs:");
Paul Hub2e67d32023-04-18 05:50:14 +00002306 pw.increaseIndent();
2307 mServiceLogs.reverseDump(pw);
2308 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002309 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002310
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002311 private abstract static class ClientRequest {
Paul Hud44e1b72023-06-16 02:07:42 +00002312 private final int mTransactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002313 private final long mStartTimeMs;
Paul Hu812e9212023-06-20 06:24:53 +00002314 private int mFoundServiceCount = 0;
2315 private int mLostServiceCount = 0;
2316 private final Set<String> mServices = new ArraySet<>();
Paul Hua6bc4632023-06-26 01:18:29 +00002317 private boolean mIsServiceFromCache = false;
Paul Hubad6fe92023-07-24 21:25:22 +08002318 private int mSentQueryCount = NO_SENT_QUERY_COUNT;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002319
Paul Hu812e9212023-06-20 06:24:53 +00002320 private ClientRequest(int transactionId, long startTimeMs) {
Paul Hud44e1b72023-06-16 02:07:42 +00002321 mTransactionId = transactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002322 mStartTimeMs = startTimeMs;
2323 }
2324
Paul Hu812e9212023-06-20 06:24:53 +00002325 public long calculateRequestDurationMs(long stopTimeMs) {
Paul Hu777ed052023-06-19 13:35:15 +00002326 return stopTimeMs - mStartTimeMs;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002327 }
Paul Hu812e9212023-06-20 06:24:53 +00002328
2329 public void onServiceFound(String serviceName) {
2330 mFoundServiceCount++;
2331 if (mServices.size() <= MAX_SERVICES_COUNT_METRIC_PER_CLIENT) {
2332 mServices.add(serviceName);
2333 }
2334 }
2335
2336 public void onServiceLost() {
2337 mLostServiceCount++;
2338 }
2339
2340 public int getFoundServiceCount() {
2341 return mFoundServiceCount;
2342 }
2343
2344 public int getLostServiceCount() {
2345 return mLostServiceCount;
2346 }
2347
2348 public int getServicesCount() {
2349 return mServices.size();
2350 }
Paul Hua6bc4632023-06-26 01:18:29 +00002351
2352 public void setServiceFromCache(boolean isServiceFromCache) {
2353 mIsServiceFromCache = isServiceFromCache;
2354 }
2355
2356 public boolean isServiceFromCache() {
2357 return mIsServiceFromCache;
2358 }
Paul Hubad6fe92023-07-24 21:25:22 +08002359
2360 public void onQuerySent() {
2361 mSentQueryCount++;
2362 }
2363
2364 public int getSentQueryCount() {
2365 return mSentQueryCount;
2366 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002367 }
2368
2369 private static class LegacyClientRequest extends ClientRequest {
2370 private final int mRequestCode;
2371
Paul Hu812e9212023-06-20 06:24:53 +00002372 private LegacyClientRequest(int transactionId, int requestCode, long startTimeMs) {
2373 super(transactionId, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002374 mRequestCode = requestCode;
2375 }
2376 }
2377
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002378 private abstract static class JavaBackendClientRequest extends ClientRequest {
2379 @Nullable
2380 private final Network mRequestedNetwork;
2381
Paul Hu777ed052023-06-19 13:35:15 +00002382 private JavaBackendClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002383 long startTimeMs) {
2384 super(transactionId, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002385 mRequestedNetwork = requestedNetwork;
2386 }
2387
2388 @Nullable
2389 public Network getRequestedNetwork() {
2390 return mRequestedNetwork;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002391 }
2392 }
2393
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002394 private static class AdvertiserClientRequest extends JavaBackendClientRequest {
Paul Hu777ed052023-06-19 13:35:15 +00002395 private AdvertiserClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002396 long startTimeMs) {
2397 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002398 }
2399 }
2400
2401 private static class DiscoveryManagerRequest extends JavaBackendClientRequest {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002402 @NonNull
2403 private final MdnsListener mListener;
2404
Paul Hud44e1b72023-06-16 02:07:42 +00002405 private DiscoveryManagerRequest(int transactionId, @NonNull MdnsListener listener,
Paul Hu812e9212023-06-20 06:24:53 +00002406 @Nullable Network requestedNetwork, long startTimeMs) {
2407 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002408 mListener = listener;
2409 }
2410 }
2411
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002412 /* Information tracked per client */
2413 private class ClientInfo {
2414
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002415 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002416 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002417 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002418 private NsdServiceInfo mResolvedService;
2419
Paul Hud44e1b72023-06-16 02:07:42 +00002420 /* A map from client request ID (listenerKey) to the request */
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002421 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08002422
Luke Huangf7277ed2021-07-12 21:15:10 +08002423 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002424 private boolean mIsPreSClient = false;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002425 private final int mUid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002426 // The flag of using java backend if the client's target SDK >= U
2427 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002428 // Store client logs
2429 private final SharedLog mClientLogs;
Paul Hucdef3532023-06-18 14:47:35 +00002430 // Report the nsd metrics data
2431 private final NetworkNsdReportedMetrics mMetrics;
Luke Huangf7277ed2021-07-12 21:15:10 +08002432
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002433 private ClientInfo(INsdManagerCallback cb, int uid, boolean useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +00002434 SharedLog sharedLog, NetworkNsdReportedMetrics metrics) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002435 mCb = cb;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002436 mUid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002437 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002438 mClientLogs = sharedLog;
2439 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Paul Hucdef3532023-06-18 14:47:35 +00002440 mMetrics = metrics;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002441 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002442
2443 @Override
2444 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06002445 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07002446 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002447 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002448 sb.append("mUseJavaBackend ").append(mUseJavaBackend).append("\n");
2449 sb.append("mUid ").append(mUid).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002450 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002451 int clientRequestId = mClientRequests.keyAt(i);
2452 sb.append("clientRequestId ")
2453 .append(clientRequestId)
2454 .append(" transactionId ").append(mClientRequests.valueAt(i).mTransactionId)
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002455 .append(" type ").append(
2456 mClientRequests.valueAt(i).getClass().getSimpleName())
2457 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07002458 }
2459 return sb.toString();
2460 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002461
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002462 private boolean isPreSClient() {
2463 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08002464 }
2465
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002466 private void setPreSClient() {
2467 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08002468 }
2469
Paul Hu812e9212023-06-20 06:24:53 +00002470 private MdnsListener unregisterMdnsListenerFromRequest(ClientRequest request) {
Paul Hue4f5f252023-02-16 21:13:47 +08002471 final MdnsListener listener =
2472 ((DiscoveryManagerRequest) request).mListener;
2473 mMdnsDiscoveryManager.unregisterListener(
2474 listener.getListenedServiceType(), listener);
Paul Hu812e9212023-06-20 06:24:53 +00002475 return listener;
Paul Hue4f5f252023-02-16 21:13:47 +08002476 }
2477
Dave Plattfeff2af2014-03-07 14:48:22 -08002478 // Remove any pending requests from the global map when we get rid of a client,
2479 // and send cancellations to the daemon.
2480 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00002481 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09002482 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002483 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002484 final int clientRequestId = mClientRequests.keyAt(i);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002485 final ClientRequest request = mClientRequests.valueAt(i);
Paul Hud44e1b72023-06-16 02:07:42 +00002486 final int transactionId = request.mTransactionId;
2487 mTransactionIdToClientInfoMap.remove(transactionId);
paulhub2225702021-11-17 09:35:33 +08002488 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002489 Log.d(TAG, "Terminating clientRequestId " + clientRequestId
2490 + " transactionId " + transactionId
2491 + " type " + mClientRequests.get(clientRequestId));
paulhub2225702021-11-17 09:35:33 +08002492 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002493
2494 if (request instanceof DiscoveryManagerRequest) {
Paul Hu812e9212023-06-20 06:24:53 +00002495 final MdnsListener listener = unregisterMdnsListenerFromRequest(request);
2496 if (listener instanceof DiscoveryListener) {
2497 mMetrics.reportServiceDiscoveryStop(transactionId,
2498 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2499 request.getFoundServiceCount(),
2500 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002501 request.getServicesCount(),
2502 request.getSentQueryCount());
Paul Hu60149052023-07-31 14:26:08 +08002503 } else if (listener instanceof ResolutionListener) {
2504 mMetrics.reportServiceResolutionStop(transactionId,
2505 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Huddce5912023-08-01 10:26:49 +08002506 } else if (listener instanceof ServiceInfoListener) {
2507 mMetrics.reportServiceInfoCallbackUnregistered(transactionId,
2508 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2509 request.getFoundServiceCount(),
2510 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002511 request.isServiceFromCache(),
2512 request.getSentQueryCount());
Paul Hu812e9212023-06-20 06:24:53 +00002513 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002514 continue;
2515 }
2516
2517 if (request instanceof AdvertiserClientRequest) {
Paul Hu043bcd42023-07-14 16:38:25 +08002518 final AdvertiserMetrics metrics =
2519 mAdvertiser.getAdvertiserMetrics(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00002520 mAdvertiser.removeService(transactionId);
Paul Hu812e9212023-06-20 06:24:53 +00002521 mMetrics.reportServiceUnregistration(transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002522 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2523 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2524 metrics.mConflictDuringProbingCount,
2525 metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002526 continue;
2527 }
2528
2529 if (!(request instanceof LegacyClientRequest)) {
2530 throw new IllegalStateException("Unknown request type: " + request.getClass());
2531 }
2532
2533 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08002534 case NsdManager.DISCOVER_SERVICES:
Paul Hud44e1b72023-06-16 02:07:42 +00002535 stopServiceDiscovery(transactionId);
Paul Hu812e9212023-06-20 06:24:53 +00002536 mMetrics.reportServiceDiscoveryStop(transactionId,
2537 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2538 request.getFoundServiceCount(),
2539 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002540 request.getServicesCount(),
2541 NO_SENT_QUERY_COUNT);
Dave Plattfeff2af2014-03-07 14:48:22 -08002542 break;
2543 case NsdManager.RESOLVE_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002544 stopResolveService(transactionId);
Paul Hu60149052023-07-31 14:26:08 +08002545 mMetrics.reportServiceResolutionStop(transactionId,
2546 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Dave Plattfeff2af2014-03-07 14:48:22 -08002547 break;
2548 case NsdManager.REGISTER_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002549 unregisterService(transactionId);
Paul Hu812e9212023-06-20 06:24:53 +00002550 mMetrics.reportServiceUnregistration(transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002551 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2552 NO_PACKET /* repliedRequestsCount */,
2553 NO_PACKET /* sentPacketCount */,
2554 0 /* conflictDuringProbingCount */,
2555 0 /* conflictAfterProbingCount */);
Dave Plattfeff2af2014-03-07 14:48:22 -08002556 break;
2557 default:
2558 break;
2559 }
2560 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002561 mClientRequests.clear();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002562 updateMulticastLock();
2563 }
2564
2565 /**
2566 * Returns true if this client has any Java backend request that requests one of the given
2567 * networks.
2568 */
2569 boolean hasAnyJavaBackendRequestForNetworks(@NonNull ArraySet<Network> networks) {
2570 for (int i = 0; i < mClientRequests.size(); i++) {
2571 final ClientRequest req = mClientRequests.valueAt(i);
2572 if (!(req instanceof JavaBackendClientRequest)) {
2573 continue;
2574 }
2575 final Network reqNetwork = ((JavaBackendClientRequest) mClientRequests.valueAt(i))
2576 .getRequestedNetwork();
2577 if (MdnsUtils.isAnyNetworkMatched(reqNetwork, networks)) {
2578 return true;
2579 }
2580 }
2581 return false;
Dave Plattfeff2af2014-03-07 14:48:22 -08002582 }
2583
Paul Hud44e1b72023-06-16 02:07:42 +00002584 // mClientRequests is a sparse array of client request id -> ClientRequest. For a given
2585 // transaction id, return the corresponding client request id.
2586 private int getClientRequestId(final int transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002587 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002588 if (mClientRequests.valueAt(i).mTransactionId == transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002589 return mClientRequests.keyAt(i);
2590 }
Christopher Lane74411222014-04-25 18:39:07 -07002591 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002592 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07002593 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002594
Paul Hub2e67d32023-04-18 05:50:14 +00002595 private void log(String message) {
2596 mClientLogs.log(message);
2597 }
2598
Paul Hu812e9212023-06-20 06:24:53 +00002599 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info, int transactionId) {
2600 mMetrics.reportServiceDiscoveryStarted(transactionId);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002601 try {
2602 mCb.onDiscoverServicesStarted(listenerKey, info);
2603 } catch (RemoteException e) {
2604 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
2605 }
2606 }
Paul Hu812e9212023-06-20 06:24:53 +00002607 void onDiscoverServicesFailedImmediately(int listenerKey, int error) {
2608 onDiscoverServicesFailed(listenerKey, error, NO_TRANSACTION, 0L /* durationMs */);
2609 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002610
Paul Hu812e9212023-06-20 06:24:53 +00002611 void onDiscoverServicesFailed(int listenerKey, int error, int transactionId,
2612 long durationMs) {
2613 mMetrics.reportServiceDiscoveryFailed(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002614 try {
2615 mCb.onDiscoverServicesFailed(listenerKey, error);
2616 } catch (RemoteException e) {
2617 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
2618 }
2619 }
2620
Paul Hu812e9212023-06-20 06:24:53 +00002621 void onServiceFound(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2622 request.onServiceFound(info.getServiceName());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002623 try {
2624 mCb.onServiceFound(listenerKey, info);
2625 } catch (RemoteException e) {
2626 Log.e(TAG, "Error calling onServiceFound(", e);
2627 }
2628 }
2629
Paul Hu812e9212023-06-20 06:24:53 +00002630 void onServiceLost(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2631 request.onServiceLost();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002632 try {
2633 mCb.onServiceLost(listenerKey, info);
2634 } catch (RemoteException e) {
2635 Log.e(TAG, "Error calling onServiceLost(", e);
2636 }
2637 }
2638
2639 void onStopDiscoveryFailed(int listenerKey, int error) {
2640 try {
2641 mCb.onStopDiscoveryFailed(listenerKey, error);
2642 } catch (RemoteException e) {
2643 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
2644 }
2645 }
2646
Paul Hu812e9212023-06-20 06:24:53 +00002647 void onStopDiscoverySucceeded(int listenerKey, ClientRequest request) {
2648 mMetrics.reportServiceDiscoveryStop(
2649 request.mTransactionId,
2650 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2651 request.getFoundServiceCount(),
2652 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002653 request.getServicesCount(),
2654 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002655 try {
2656 mCb.onStopDiscoverySucceeded(listenerKey);
2657 } catch (RemoteException e) {
2658 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2659 }
2660 }
2661
Paul Hu777ed052023-06-19 13:35:15 +00002662 void onRegisterServiceFailedImmediately(int listenerKey, int error) {
Paul Hu812e9212023-06-20 06:24:53 +00002663 onRegisterServiceFailed(listenerKey, error, NO_TRANSACTION, 0L /* durationMs */);
Paul Hu777ed052023-06-19 13:35:15 +00002664 }
2665
2666 void onRegisterServiceFailed(int listenerKey, int error, int transactionId,
2667 long durationMs) {
2668 mMetrics.reportServiceRegistrationFailed(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002669 try {
2670 mCb.onRegisterServiceFailed(listenerKey, error);
2671 } catch (RemoteException e) {
2672 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2673 }
2674 }
2675
Paul Hu777ed052023-06-19 13:35:15 +00002676 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info, int transactionId,
2677 long durationMs) {
2678 mMetrics.reportServiceRegistrationSucceeded(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002679 try {
2680 mCb.onRegisterServiceSucceeded(listenerKey, info);
2681 } catch (RemoteException e) {
2682 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2683 }
2684 }
2685
2686 void onUnregisterServiceFailed(int listenerKey, int error) {
2687 try {
2688 mCb.onUnregisterServiceFailed(listenerKey, error);
2689 } catch (RemoteException e) {
2690 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2691 }
2692 }
2693
Paul Hu043bcd42023-07-14 16:38:25 +08002694 void onUnregisterServiceSucceeded(int listenerKey, int transactionId, long durationMs,
2695 AdvertiserMetrics metrics) {
2696 mMetrics.reportServiceUnregistration(transactionId, durationMs,
2697 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2698 metrics.mConflictDuringProbingCount, metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002699 try {
2700 mCb.onUnregisterServiceSucceeded(listenerKey);
2701 } catch (RemoteException e) {
2702 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2703 }
2704 }
2705
Paul Hua6bc4632023-06-26 01:18:29 +00002706 void onResolveServiceFailedImmediately(int listenerKey, int error) {
2707 onResolveServiceFailed(listenerKey, error, NO_TRANSACTION, 0L /* durationMs */);
2708 }
2709
2710 void onResolveServiceFailed(int listenerKey, int error, int transactionId,
2711 long durationMs) {
2712 mMetrics.reportServiceResolutionFailed(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002713 try {
2714 mCb.onResolveServiceFailed(listenerKey, error);
2715 } catch (RemoteException e) {
2716 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2717 }
2718 }
2719
Paul Hua6bc4632023-06-26 01:18:29 +00002720 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info,
2721 ClientRequest request) {
2722 mMetrics.reportServiceResolved(
2723 request.mTransactionId,
2724 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hubad6fe92023-07-24 21:25:22 +08002725 request.isServiceFromCache(),
2726 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002727 try {
2728 mCb.onResolveServiceSucceeded(listenerKey, info);
2729 } catch (RemoteException e) {
2730 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2731 }
2732 }
Paul Hub58deb72022-12-26 09:24:42 +00002733
2734 void onStopResolutionFailed(int listenerKey, int error) {
2735 try {
2736 mCb.onStopResolutionFailed(listenerKey, error);
2737 } catch (RemoteException e) {
2738 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2739 }
2740 }
2741
Paul Hu60149052023-07-31 14:26:08 +08002742 void onStopResolutionSucceeded(int listenerKey, ClientRequest request) {
2743 mMetrics.reportServiceResolutionStop(
2744 request.mTransactionId,
2745 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hub58deb72022-12-26 09:24:42 +00002746 try {
2747 mCb.onStopResolutionSucceeded(listenerKey);
2748 } catch (RemoteException e) {
2749 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2750 }
2751 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002752
2753 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
Paul Huddce5912023-08-01 10:26:49 +08002754 mMetrics.reportServiceInfoCallbackRegistrationFailed(NO_TRANSACTION);
Paul Hu18aeccc2022-12-27 08:48:48 +00002755 try {
2756 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2757 } catch (RemoteException e) {
2758 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2759 }
2760 }
2761
Paul Huddce5912023-08-01 10:26:49 +08002762 void onServiceInfoCallbackRegistered(int transactionId) {
2763 mMetrics.reportServiceInfoCallbackRegistered(transactionId);
2764 }
2765
2766 void onServiceUpdated(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2767 request.onServiceFound(info.getServiceName());
Paul Hu18aeccc2022-12-27 08:48:48 +00002768 try {
2769 mCb.onServiceUpdated(listenerKey, info);
2770 } catch (RemoteException e) {
2771 Log.e(TAG, "Error calling onServiceUpdated", e);
2772 }
2773 }
2774
Paul Huddce5912023-08-01 10:26:49 +08002775 void onServiceUpdatedLost(int listenerKey, ClientRequest request) {
2776 request.onServiceLost();
Paul Hu18aeccc2022-12-27 08:48:48 +00002777 try {
2778 mCb.onServiceUpdatedLost(listenerKey);
2779 } catch (RemoteException e) {
2780 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2781 }
2782 }
2783
Paul Huddce5912023-08-01 10:26:49 +08002784 void onServiceInfoCallbackUnregistered(int listenerKey, ClientRequest request) {
2785 mMetrics.reportServiceInfoCallbackUnregistered(
2786 request.mTransactionId,
2787 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2788 request.getFoundServiceCount(),
2789 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002790 request.isServiceFromCache(),
2791 request.getSentQueryCount());
Paul Hu18aeccc2022-12-27 08:48:48 +00002792 try {
2793 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2794 } catch (RemoteException e) {
2795 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2796 }
2797 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002798 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002799}