blob: 745c5bc705d14ec42df1fddf21fcdfdca820b63a [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
paulhu2b9ed952022-02-10 21:58:32 +080019import static android.net.ConnectivityManager.NETID_UNSET;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090020import static android.net.NetworkCapabilities.TRANSPORT_VPN;
21import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
Paul Hu019621e2023-01-13 23:26:49 +080022import static android.net.nsd.NsdManager.MDNS_DISCOVERY_MANAGER_EVENT;
paulhu2b9ed952022-02-10 21:58:32 +080023import static android.net.nsd.NsdManager.MDNS_SERVICE_EVENT;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +090024import static android.net.nsd.NsdManager.RESOLVE_SERVICE_SUCCEEDED;
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +090025import static android.provider.DeviceConfig.NAMESPACE_TETHERING;
paulhu2b9ed952022-02-10 21:58:32 +080026
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090027import static com.android.modules.utils.build.SdkLevel.isAtLeastU;
Yuyang Huangde802c82023-05-02 17:14:22 +090028import static com.android.server.connectivity.mdns.MdnsRecord.MAX_LABEL_LENGTH;
Paul Hucdef3532023-06-18 14:47:35 +000029import static com.android.server.connectivity.mdns.util.MdnsUtils.Clock;
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090030
Paul Hu23fa2022023-01-13 22:57:24 +080031import android.annotation.NonNull;
Paul Hu4bd98ef2023-01-12 13:42:07 +080032import android.annotation.Nullable;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090033import android.app.ActivityManager;
paulhua262cc12019-08-12 16:25:11 +080034import android.content.Context;
Irfan Sheriff75006652012-04-17 23:15:29 -070035import android.content.Intent;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090036import android.net.ConnectivityManager;
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +090037import android.net.INetd;
Paul Hu75069ed2023-01-14 00:31:09 +080038import android.net.InetAddresses;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090039import android.net.LinkProperties;
40import android.net.Network;
paulhu2b9ed952022-02-10 21:58:32 +080041import android.net.mdns.aidl.DiscoveryInfo;
42import android.net.mdns.aidl.GetAddressInfo;
43import android.net.mdns.aidl.IMDnsEventListener;
44import android.net.mdns.aidl.RegistrationInfo;
45import android.net.mdns.aidl.ResolutionInfo;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070046import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090047import android.net.nsd.INsdManagerCallback;
48import android.net.nsd.INsdServiceConnector;
paulhu2b9ed952022-02-10 21:58:32 +080049import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070050import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080051import android.net.nsd.NsdServiceInfo;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090052import android.net.wifi.WifiManager;
Paul Hub2e67d32023-04-18 05:50:14 +000053import android.os.Binder;
Hugo Benichi803a2f02017-04-24 11:35:06 +090054import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080055import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090056import android.os.IBinder;
Paul Hu4bd98ef2023-01-12 13:42:07 +080057import android.os.Looper;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070058import android.os.Message;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090059import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070060import android.os.UserHandle;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090061import android.provider.DeviceConfig;
Paul Hu23fa2022023-01-13 22:57:24 +080062import android.text.TextUtils;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090063import android.util.ArraySet;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090064import android.util.Log;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +090065import android.util.Pair;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070066import android.util.SparseArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070067
paulhua262cc12019-08-12 16:25:11 +080068import com.android.internal.annotations.VisibleForTesting;
Paul Hub2e67d32023-04-18 05:50:14 +000069import com.android.internal.util.IndentingPrintWriter;
paulhua262cc12019-08-12 16:25:11 +080070import com.android.internal.util.State;
71import com.android.internal.util.StateMachine;
Paul Hucdef3532023-06-18 14:47:35 +000072import com.android.metrics.NetworkNsdReportedMetrics;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090073import com.android.net.module.util.CollectionUtils;
Paul Hu4bd98ef2023-01-12 13:42:07 +080074import com.android.net.module.util.DeviceConfigUtils;
Yuyang Huanga6a6ff92023-04-24 13:33:34 +090075import com.android.net.module.util.InetAddressUtils;
paulhu3ffffe72021-09-16 10:15:22 +080076import com.android.net.module.util.PermissionUtils;
Paul Hub2e67d32023-04-18 05:50:14 +000077import com.android.net.module.util.SharedLog;
Paul Hu4bd98ef2023-01-12 13:42:07 +080078import com.android.server.connectivity.mdns.ExecutorProvider;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090079import com.android.server.connectivity.mdns.MdnsAdvertiser;
Paul Hu4bd98ef2023-01-12 13:42:07 +080080import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090081import com.android.server.connectivity.mdns.MdnsInterfaceSocket;
Paul Hu4bd98ef2023-01-12 13:42:07 +080082import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
Paul Hu23fa2022023-01-13 22:57:24 +080083import com.android.server.connectivity.mdns.MdnsSearchOptions;
84import com.android.server.connectivity.mdns.MdnsServiceBrowserListener;
85import com.android.server.connectivity.mdns.MdnsServiceInfo;
Paul Hu4bd98ef2023-01-12 13:42:07 +080086import com.android.server.connectivity.mdns.MdnsSocketProvider;
Yuyang Huangde802c82023-05-02 17:14:22 +090087import com.android.server.connectivity.mdns.util.MdnsUtils;
paulhua262cc12019-08-12 16:25:11 +080088
Irfan Sheriff77ec5582012-03-22 17:01:39 -070089import java.io.FileDescriptor;
90import java.io.PrintWriter;
Yuyang Huangaa0e9602023-03-17 12:43:09 +090091import java.net.Inet6Address;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070092import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090093import java.net.NetworkInterface;
94import java.net.SocketException;
95import java.net.UnknownHostException;
Paul Hu2b865912023-03-06 14:27:53 +080096import java.util.ArrayList;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +090097import java.util.Arrays;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070098import java.util.HashMap;
Paul Hu23fa2022023-01-13 22:57:24 +080099import java.util.List;
Paul Hu75069ed2023-01-14 00:31:09 +0800100import java.util.Map;
Paul Hu23fa2022023-01-13 22:57:24 +0800101import java.util.regex.Matcher;
102import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700103
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700104/**
105 * Network Service Discovery Service handles remote service discovery operation requests by
106 * implementing the INsdManager interface.
107 *
108 * @hide
109 */
110public class NsdService extends INsdManager.Stub {
111 private static final String TAG = "NsdService";
112 private static final String MDNS_TAG = "mDnsConnector";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900113 /**
114 * Enable discovery using the Java DiscoveryManager, instead of the legacy mdnsresponder
115 * implementation.
116 */
Paul Hu4bd98ef2023-01-12 13:42:07 +0800117 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +0800118 private static final String LOCAL_DOMAIN_NAME = "local";
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700119
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900120 /**
121 * Enable advertising using the Java MdnsAdvertiser, instead of the legacy mdnsresponder
122 * implementation.
123 */
124 private static final String MDNS_ADVERTISER_VERSION = "mdns_advertiser_version";
125
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900126 /**
127 * Comma-separated list of type:flag mappings indicating the flags to use to allowlist
128 * discovery/advertising using MdnsDiscoveryManager / MdnsAdvertiser for a given type.
129 *
130 * For example _mytype._tcp.local and _othertype._tcp.local would be configured with:
131 * _mytype._tcp:mytype,_othertype._tcp.local:othertype
132 *
133 * In which case the flags:
134 * "mdns_discovery_manager_allowlist_mytype_version",
135 * "mdns_advertiser_allowlist_mytype_version",
136 * "mdns_discovery_manager_allowlist_othertype_version",
137 * "mdns_advertiser_allowlist_othertype_version"
138 * would be used to toggle MdnsDiscoveryManager / MdnsAdvertiser for each type. The flags will
139 * be read with
140 * {@link DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)}.
141 *
142 * @see #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX
143 * @see #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX
144 * @see #MDNS_ALLOWLIST_FLAG_SUFFIX
145 */
146 private static final String MDNS_TYPE_ALLOWLIST_FLAGS = "mdns_type_allowlist_flags";
147
148 private static final String MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX =
149 "mdns_discovery_manager_allowlist_";
150 private static final String MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX =
151 "mdns_advertiser_allowlist_";
152 private static final String MDNS_ALLOWLIST_FLAG_SUFFIX = "_version";
153
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900154 @VisibleForTesting
155 static final String MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
156 "mdns_config_running_app_active_importance_cutoff";
157 @VisibleForTesting
158 static final int DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
159 ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
160 private final int mRunningAppActiveImportanceCutoff;
161
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900162 public static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +0000163 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900164 private static final int IFACE_IDX_ANY = 0;
Paul Hu777ed052023-06-19 13:35:15 +0000165 private static final int NO_TRANSACTION = -1;
Paul Hu14667de2023-04-17 22:42:47 +0800166 private static final SharedLog LOGGER = new SharedLog("serviceDiscovery");
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700167
Hugo Benichi32be63d2017-04-05 14:06:11 +0900168 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900169 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +0800170 private final MDnsManager mMDnsManager;
171 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900172 @NonNull
173 private final Dependencies mDeps;
174 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800175 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900176 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800177 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900178 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800179 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900180 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900181 private final MdnsAdvertiser mAdvertiser;
Paul Hu777ed052023-06-19 13:35:15 +0000182 @NonNull
183 private final Clock mClock;
Paul Hu14667de2023-04-17 22:42:47 +0800184 private final SharedLog mServiceLogs = LOGGER.forSubComponent(TAG);
Paul Hu23fa2022023-01-13 22:57:24 +0800185 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800186 // state machine thread. If change this outside state machine, it will need to introduce
187 // synchronization.
188 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800189 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700190
191 /**
192 * Clients receiving asynchronous messages
193 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900194 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700195
Paul Hud44e1b72023-06-16 02:07:42 +0000196 /* A map from transaction(unique) id to client info */
197 private final SparseArray<ClientInfo> mTransactionIdToClientInfoMap = new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700198
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900199 // Note this is not final to avoid depending on the Wi-Fi service starting before NsdService
200 @Nullable
201 private WifiManager.MulticastLock mHeldMulticastLock;
202 // Fulfilled network requests that require the Wi-Fi lock: key is the obtained Network
203 // (non-null), value is the requested Network (nullable)
204 @NonNull
205 private final ArraySet<Network> mWifiLockRequiredNetworks = new ArraySet<>();
206 @NonNull
207 private final ArraySet<Integer> mRunningAppActiveUids = new ArraySet<>();
208
Luke Huang05298582021-06-13 16:52:05 +0000209 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700210
Hugo Benichi32be63d2017-04-05 14:06:11 +0900211 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700212 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800213 // The count of the connected legacy clients.
214 private int mLegacyClientCount = 0;
Paul Hub2e67d32023-04-18 05:50:14 +0000215 // The number of client that ever connected.
216 private int mClientNumberId = 1;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700217
Paul Hu23fa2022023-01-13 22:57:24 +0800218 private static class MdnsListener implements MdnsServiceBrowserListener {
Paul Hud44e1b72023-06-16 02:07:42 +0000219 protected final int mClientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800220 protected final int mTransactionId;
221 @NonNull
222 protected final NsdServiceInfo mReqServiceInfo;
223 @NonNull
224 protected final String mListenedServiceType;
225
Paul Hud44e1b72023-06-16 02:07:42 +0000226 MdnsListener(int clientRequestId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
Paul Hu23fa2022023-01-13 22:57:24 +0800227 @NonNull String listenedServiceType) {
Paul Hud44e1b72023-06-16 02:07:42 +0000228 mClientRequestId = clientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800229 mTransactionId = transactionId;
230 mReqServiceInfo = reqServiceInfo;
231 mListenedServiceType = listenedServiceType;
232 }
233
234 @NonNull
235 public String getListenedServiceType() {
236 return mListenedServiceType;
237 }
238
239 @Override
240 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) { }
241
242 @Override
243 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
244
245 @Override
246 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
247
248 @Override
249 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) { }
250
251 @Override
252 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
253
254 @Override
255 public void onSearchStoppedWithError(int error) { }
256
257 @Override
258 public void onSearchFailedToStart() { }
259
260 @Override
261 public void onDiscoveryQuerySent(@NonNull List<String> subtypes, int transactionId) { }
262
263 @Override
264 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
265 }
266
267 private class DiscoveryListener extends MdnsListener {
268
Paul Hud44e1b72023-06-16 02:07:42 +0000269 DiscoveryListener(int clientRequestId, int transactionId,
270 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
271 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800272 }
273
274 @Override
275 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu019621e2023-01-13 23:26:49 +0800276 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
277 NsdManager.SERVICE_FOUND,
Paul Hud44e1b72023-06-16 02:07:42 +0000278 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800279 }
280
281 @Override
282 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800283 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
284 NsdManager.SERVICE_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000285 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800286 }
287 }
288
Paul Hu75069ed2023-01-14 00:31:09 +0800289 private class ResolutionListener extends MdnsListener {
290
Paul Hud44e1b72023-06-16 02:07:42 +0000291 ResolutionListener(int clientRequestId, int transactionId,
292 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
293 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800294 }
295
296 @Override
297 public void onServiceFound(MdnsServiceInfo serviceInfo) {
298 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
299 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
Paul Hud44e1b72023-06-16 02:07:42 +0000300 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu75069ed2023-01-14 00:31:09 +0800301 }
302 }
303
Paul Hu30bd70d2023-02-07 13:20:56 +0000304 private class ServiceInfoListener extends MdnsListener {
305
Paul Hud44e1b72023-06-16 02:07:42 +0000306 ServiceInfoListener(int clientRequestId, int transactionId,
307 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
308 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +0000309 }
310
311 @Override
312 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) {
313 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
314 NsdManager.SERVICE_UPDATED,
Paul Hud44e1b72023-06-16 02:07:42 +0000315 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000316 }
317
318 @Override
319 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) {
320 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
321 NsdManager.SERVICE_UPDATED,
Paul Hud44e1b72023-06-16 02:07:42 +0000322 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000323 }
324
325 @Override
326 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) {
327 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
328 NsdManager.SERVICE_UPDATED_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000329 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000330 }
331 }
332
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900333 private class SocketRequestMonitor implements MdnsSocketProvider.SocketRequestMonitor {
334 @Override
335 public void onSocketRequestFulfilled(@Nullable Network socketNetwork,
336 @NonNull MdnsInterfaceSocket socket, @NonNull int[] transports) {
337 // The network may be null for Wi-Fi SoftAp interfaces (tethering), but there is no APF
338 // filtering on such interfaces, so taking the multicast lock is not necessary to
339 // disable APF filtering of multicast.
340 if (socketNetwork == null
341 || !CollectionUtils.contains(transports, TRANSPORT_WIFI)
342 || CollectionUtils.contains(transports, TRANSPORT_VPN)) {
343 return;
344 }
345
346 if (mWifiLockRequiredNetworks.add(socketNetwork)) {
347 updateMulticastLock();
348 }
349 }
350
351 @Override
352 public void onSocketDestroyed(@Nullable Network socketNetwork,
353 @NonNull MdnsInterfaceSocket socket) {
354 if (mWifiLockRequiredNetworks.remove(socketNetwork)) {
355 updateMulticastLock();
356 }
357 }
358 }
359
360 private class UidImportanceListener implements ActivityManager.OnUidImportanceListener {
361 private final Handler mHandler;
362
363 private UidImportanceListener(Handler handler) {
364 mHandler = handler;
365 }
366
367 @Override
368 public void onUidImportance(int uid, int importance) {
369 mHandler.post(() -> handleUidImportanceChanged(uid, importance));
370 }
371 }
372
373 private void handleUidImportanceChanged(int uid, int importance) {
374 // Lower importance values are more "important"
375 final boolean modified = importance <= mRunningAppActiveImportanceCutoff
376 ? mRunningAppActiveUids.add(uid)
377 : mRunningAppActiveUids.remove(uid);
378 if (modified) {
379 updateMulticastLock();
380 }
381 }
382
383 /**
384 * Take or release the lock based on updated internal state.
385 *
386 * This determines whether the lock needs to be held based on
387 * {@link #mWifiLockRequiredNetworks}, {@link #mRunningAppActiveUids} and
388 * {@link ClientInfo#mClientRequests}, so it must be called after any of the these have been
389 * updated.
390 */
391 private void updateMulticastLock() {
392 final int needsLockUid = getMulticastLockNeededUid();
393 if (needsLockUid >= 0 && mHeldMulticastLock == null) {
394 final WifiManager wm = mContext.getSystemService(WifiManager.class);
395 if (wm == null) {
396 Log.wtf(TAG, "Got a TRANSPORT_WIFI network without WifiManager");
397 return;
398 }
399 mHeldMulticastLock = wm.createMulticastLock(TAG);
400 mHeldMulticastLock.acquire();
401 mServiceLogs.log("Taking multicast lock for uid " + needsLockUid);
402 } else if (needsLockUid < 0 && mHeldMulticastLock != null) {
403 mHeldMulticastLock.release();
404 mHeldMulticastLock = null;
405 mServiceLogs.log("Released multicast lock");
406 }
407 }
408
409 /**
410 * @return The UID of an app requiring the multicast lock, or -1 if none.
411 */
412 private int getMulticastLockNeededUid() {
413 if (mWifiLockRequiredNetworks.size() == 0) {
414 // Return early if NSD is not active, or not on any relevant network
415 return -1;
416 }
Paul Hud44e1b72023-06-16 02:07:42 +0000417 for (int i = 0; i < mTransactionIdToClientInfoMap.size(); i++) {
418 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.valueAt(i);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900419 if (!mRunningAppActiveUids.contains(clientInfo.mUid)) {
420 // Ignore non-active UIDs
421 continue;
422 }
423
424 if (clientInfo.hasAnyJavaBackendRequestForNetworks(mWifiLockRequiredNetworks)) {
425 return clientInfo.mUid;
426 }
427 }
428 return -1;
429 }
430
Paul Hu019621e2023-01-13 23:26:49 +0800431 /**
432 * Data class of mdns service callback information.
433 */
434 private static class MdnsEvent {
Paul Hud44e1b72023-06-16 02:07:42 +0000435 final int mClientRequestId;
Paul Hu019621e2023-01-13 23:26:49 +0800436 @NonNull
Paul Hu019621e2023-01-13 23:26:49 +0800437 final MdnsServiceInfo mMdnsServiceInfo;
438
Paul Hud44e1b72023-06-16 02:07:42 +0000439 MdnsEvent(int clientRequestId, @NonNull MdnsServiceInfo mdnsServiceInfo) {
440 mClientRequestId = clientRequestId;
Paul Hu019621e2023-01-13 23:26:49 +0800441 mMdnsServiceInfo = mdnsServiceInfo;
442 }
443 }
444
Irfan Sheriff75006652012-04-17 23:15:29 -0700445 private class NsdStateMachine extends StateMachine {
446
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700447 private final DefaultState mDefaultState = new DefaultState();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700448 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700449
450 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700451 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900452 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700453 }
454
Luke Huang92860f92021-06-23 06:29:30 +0000455 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800456 if (mIsDaemonStarted) {
457 if (DBG) Log.d(TAG, "Daemon is already started.");
458 return;
459 }
460 mMDnsManager.registerEventListener(mMDnsEventCallback);
461 mMDnsManager.startDaemon();
462 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000463 maybeScheduleStop();
Paul Hub2e67d32023-04-18 05:50:14 +0000464 mServiceLogs.log("Start mdns_responder daemon");
Luke Huang05298582021-06-13 16:52:05 +0000465 }
466
paulhu2b9ed952022-02-10 21:58:32 +0800467 private void maybeStopDaemon() {
468 if (!mIsDaemonStarted) {
469 if (DBG) Log.d(TAG, "Daemon has not been started.");
470 return;
471 }
472 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
473 mMDnsManager.stopDaemon();
474 mIsDaemonStarted = false;
Paul Hub2e67d32023-04-18 05:50:14 +0000475 mServiceLogs.log("Stop mdns_responder daemon");
paulhu2b9ed952022-02-10 21:58:32 +0800476 }
477
Luke Huang92860f92021-06-23 06:29:30 +0000478 private boolean isAnyRequestActive() {
Paul Hud44e1b72023-06-16 02:07:42 +0000479 return mTransactionIdToClientInfoMap.size() != 0;
Luke Huang92860f92021-06-23 06:29:30 +0000480 }
481
482 private void scheduleStop() {
483 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
484 }
485 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800486 // The native daemon should stay alive and can't be cleanup
487 // if any legacy client connected.
488 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000489 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000490 }
491 }
492
Luke Huang92860f92021-06-23 06:29:30 +0000493 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000494 this.removeMessages(NsdManager.DAEMON_CLEANUP);
495 }
496
Paul Hu23fa2022023-01-13 22:57:24 +0800497 private void maybeStartMonitoringSockets() {
498 if (mIsMonitoringSocketsStarted) {
499 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
500 return;
501 }
502
503 mMdnsSocketProvider.startMonitoringSockets();
504 mIsMonitoringSocketsStarted = true;
505 }
506
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900507 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
508 if (!mIsMonitoringSocketsStarted) return;
509 if (isAnyRequestActive()) return;
510
Paul Hu58f20602023-02-18 11:41:07 +0800511 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800512 mIsMonitoringSocketsStarted = false;
513 }
514
Hugo Benichi803a2f02017-04-24 11:35:06 +0900515 NsdStateMachine(String name, Handler handler) {
516 super(name, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700517 addState(mDefaultState);
Irfan Sheriff75006652012-04-17 23:15:29 -0700518 addState(mEnabledState, mDefaultState);
paulhu5568f452021-11-30 13:31:29 +0800519 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900520 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700521 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700522 }
523
524 class DefaultState extends State {
525 @Override
526 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900527 final ClientInfo cInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000528 final int clientRequestId = msg.arg2;
Irfan Sheriff75006652012-04-17 23:15:29 -0700529 switch (msg.what) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900530 case NsdManager.REGISTER_CLIENT:
Paul Hu2e0a88c2023-03-09 16:05:01 +0800531 final ConnectorArgs arg = (ConnectorArgs) msg.obj;
532 final INsdManagerCallback cb = arg.callback;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900533 try {
Paul Hu2e0a88c2023-03-09 16:05:01 +0800534 cb.asBinder().linkToDeath(arg.connector, 0);
Paul Hub2e67d32023-04-18 05:50:14 +0000535 final String tag = "Client" + arg.uid + "-" + mClientNumberId++;
Paul Hu777ed052023-06-19 13:35:15 +0000536 final NetworkNsdReportedMetrics metrics =
537 mDeps.makeNetworkNsdReportedMetrics(
538 !arg.useJavaBackend, (int) mClock.elapsedRealtime());
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900539 cInfo = new ClientInfo(cb, arg.uid, arg.useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +0000540 mServiceLogs.forSubComponent(tag), metrics);
Paul Hu2e0a88c2023-03-09 16:05:01 +0800541 mClients.put(arg.connector, cInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900542 } catch (RemoteException e) {
Paul Hud44e1b72023-06-16 02:07:42 +0000543 Log.w(TAG, "Client request id " + clientRequestId
544 + " has already died");
Irfan Sheriff75006652012-04-17 23:15:29 -0700545 }
546 break;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900547 case NsdManager.UNREGISTER_CLIENT:
548 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
549 cInfo = mClients.remove(connector);
Dave Plattfeff2af2014-03-07 14:48:22 -0800550 if (cInfo != null) {
551 cInfo.expungeAllRequests();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900552 if (cInfo.isPreSClient()) {
Luke Huangf7277ed2021-07-12 21:15:10 +0800553 mLegacyClientCount -= 1;
554 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800555 }
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900556 maybeStopMonitoringSocketsIfNoActiveRequest();
Luke Huangf7277ed2021-07-12 21:15:10 +0800557 maybeScheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700558 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700559 case NsdManager.DISCOVER_SERVICES:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900560 cInfo = getClientInfoForReply(msg);
561 if (cInfo != null) {
562 cInfo.onDiscoverServicesFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000563 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900564 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700565 break;
566 case NsdManager.STOP_DISCOVERY:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900567 cInfo = getClientInfoForReply(msg);
568 if (cInfo != null) {
569 cInfo.onStopDiscoveryFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000570 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900571 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700572 break;
573 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900574 cInfo = getClientInfoForReply(msg);
575 if (cInfo != null) {
Paul Hu777ed052023-06-19 13:35:15 +0000576 cInfo.onRegisterServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000577 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900578 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700579 break;
580 case NsdManager.UNREGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900581 cInfo = getClientInfoForReply(msg);
582 if (cInfo != null) {
583 cInfo.onUnregisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000584 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900585 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700586 break;
587 case NsdManager.RESOLVE_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900588 cInfo = getClientInfoForReply(msg);
589 if (cInfo != null) {
590 cInfo.onResolveServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000591 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900592 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700593 break;
Paul Hub58deb72022-12-26 09:24:42 +0000594 case NsdManager.STOP_RESOLUTION:
595 cInfo = getClientInfoForReply(msg);
596 if (cInfo != null) {
597 cInfo.onStopResolutionFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000598 clientRequestId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hub58deb72022-12-26 09:24:42 +0000599 }
600 break;
Paul Hu18aeccc2022-12-27 08:48:48 +0000601 case NsdManager.REGISTER_SERVICE_CALLBACK:
602 cInfo = getClientInfoForReply(msg);
603 if (cInfo != null) {
604 cInfo.onServiceInfoCallbackRegistrationFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000605 clientRequestId, NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +0000606 }
607 break;
Luke Huang05298582021-06-13 16:52:05 +0000608 case NsdManager.DAEMON_CLEANUP:
paulhu2b9ed952022-02-10 21:58:32 +0800609 maybeStopDaemon();
Luke Huang05298582021-06-13 16:52:05 +0000610 break;
Luke Huangf7277ed2021-07-12 21:15:10 +0800611 // This event should be only sent by the legacy (target SDK < S) clients.
612 // Mark the sending client as legacy.
613 case NsdManager.DAEMON_STARTUP:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900614 cInfo = getClientInfoForReply(msg);
Luke Huangf7277ed2021-07-12 21:15:10 +0800615 if (cInfo != null) {
616 cancelStop();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900617 cInfo.setPreSClient();
Luke Huangf7277ed2021-07-12 21:15:10 +0800618 mLegacyClientCount += 1;
619 maybeStartDaemon();
620 }
621 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700622 default:
paulhub2225702021-11-17 09:35:33 +0800623 Log.e(TAG, "Unhandled " + msg);
Irfan Sheriff75006652012-04-17 23:15:29 -0700624 return NOT_HANDLED;
625 }
626 return HANDLED;
627 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900628
629 private ClientInfo getClientInfoForReply(Message msg) {
630 final ListenerArgs args = (ListenerArgs) msg.obj;
631 return mClients.get(args.connector);
632 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700633 }
634
Irfan Sheriff75006652012-04-17 23:15:29 -0700635 class EnabledState extends State {
636 @Override
637 public void enter() {
638 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700639 }
640
641 @Override
642 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000643 // TODO: it is incorrect to stop the daemon without expunging all requests
644 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000645 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700646 }
647
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700648 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900649 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800650 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700651 return true;
652 }
653 return false;
654 }
655
Paul Hud44e1b72023-06-16 02:07:42 +0000656 private void storeLegacyRequestMap(int clientRequestId, int transactionId,
657 ClientInfo clientInfo, int what) {
Paul Hu777ed052023-06-19 13:35:15 +0000658 clientInfo.mClientRequests.put(clientRequestId, new LegacyClientRequest(
659 transactionId, what, mClock, mClock.elapsedRealtime()));
Paul Hud44e1b72023-06-16 02:07:42 +0000660 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000661 // Remove the cleanup event because here comes a new request.
662 cancelStop();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700663 }
664
Paul Hud44e1b72023-06-16 02:07:42 +0000665 private void storeAdvertiserRequestMap(int clientRequestId, int transactionId,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900666 ClientInfo clientInfo, @Nullable Network requestedNetwork) {
Paul Hu777ed052023-06-19 13:35:15 +0000667 clientInfo.mClientRequests.put(clientRequestId, new AdvertiserClientRequest(
668 transactionId, requestedNetwork, mClock, mClock.elapsedRealtime()));
Paul Hud44e1b72023-06-16 02:07:42 +0000669 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900670 updateMulticastLock();
Paul Hu23fa2022023-01-13 22:57:24 +0800671 }
672
Paul Hud44e1b72023-06-16 02:07:42 +0000673 private void removeRequestMap(
674 int clientRequestId, int transactionId, ClientInfo clientInfo) {
675 final ClientRequest existing = clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900676 if (existing == null) return;
Paul Hud44e1b72023-06-16 02:07:42 +0000677 clientInfo.mClientRequests.remove(clientRequestId);
678 mTransactionIdToClientInfoMap.remove(transactionId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900679
680 if (existing instanceof LegacyClientRequest) {
681 maybeScheduleStop();
682 } else {
683 maybeStopMonitoringSocketsIfNoActiveRequest();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900684 updateMulticastLock();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900685 }
686 }
687
Paul Hud44e1b72023-06-16 02:07:42 +0000688 private void storeDiscoveryManagerRequestMap(int clientRequestId, int transactionId,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900689 MdnsListener listener, ClientInfo clientInfo,
690 @Nullable Network requestedNetwork) {
Paul Hu777ed052023-06-19 13:35:15 +0000691 clientInfo.mClientRequests.put(clientRequestId, new DiscoveryManagerRequest(
692 transactionId, listener, requestedNetwork, mClock,
693 mClock.elapsedRealtime()));
Paul Hud44e1b72023-06-16 02:07:42 +0000694 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900695 updateMulticastLock();
Paul Hu23fa2022023-01-13 22:57:24 +0800696 }
697
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900698 /**
699 * Truncate a service name to up to 63 UTF-8 bytes.
700 *
701 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
702 * names used in registerService follows historical behavior (see mdnsresponder
703 * handle_regservice_request).
704 */
705 @NonNull
706 private String truncateServiceName(@NonNull String originalName) {
Yuyang Huangde802c82023-05-02 17:14:22 +0900707 return MdnsUtils.truncateServiceName(originalName, MAX_LABEL_LENGTH);
Paul Hu23fa2022023-01-13 22:57:24 +0800708 }
709
Paul Hud44e1b72023-06-16 02:07:42 +0000710 private void stopDiscoveryManagerRequest(ClientRequest request, int clientRequestId,
711 int transactionId, ClientInfo clientInfo) {
Paul Hue4f5f252023-02-16 21:13:47 +0800712 clientInfo.unregisterMdnsListenerFromRequest(request);
Paul Hud44e1b72023-06-16 02:07:42 +0000713 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hue4f5f252023-02-16 21:13:47 +0800714 }
715
Irfan Sheriff75006652012-04-17 23:15:29 -0700716 @Override
717 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900718 final ClientInfo clientInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000719 final int transactionId;
720 final int clientRequestId = msg.arg2;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900721 final ListenerArgs args;
Irfan Sheriff75006652012-04-17 23:15:29 -0700722 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800723 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800724 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900725 args = (ListenerArgs) msg.obj;
726 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000727 // If the binder death notification for a INsdManagerCallback was received
728 // before any calls are received by NsdService, the clientInfo would be
729 // cleared and cause NPE. Add a null check here to prevent this corner case.
730 if (clientInfo == null) {
731 Log.e(TAG, "Unknown connector in discovery");
732 break;
733 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700734
735 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900736 clientInfo.onDiscoverServicesFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000737 clientRequestId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriff75006652012-04-17 23:15:29 -0700738 break;
739 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700740
Paul Hu23fa2022023-01-13 22:57:24 +0800741 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000742 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900743 final Pair<String, String> typeAndSubtype =
744 parseTypeAndSubtype(info.getServiceType());
745 final String serviceType = typeAndSubtype == null
746 ? null : typeAndSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800747 if (clientInfo.mUseJavaBackend
748 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900749 || useDiscoveryManagerForType(serviceType)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800750 if (serviceType == null) {
Paul Hud44e1b72023-06-16 02:07:42 +0000751 clientInfo.onDiscoverServicesFailed(clientRequestId,
Paul Hu23fa2022023-01-13 22:57:24 +0800752 NsdManager.FAILURE_INTERNAL_ERROR);
753 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700754 }
Paul Hu23fa2022023-01-13 22:57:24 +0800755
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900756 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800757 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +0000758 final MdnsListener listener = new DiscoveryListener(clientRequestId,
759 transactionId, info, listenServiceType);
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900760 final MdnsSearchOptions.Builder optionsBuilder =
761 MdnsSearchOptions.newBuilder()
762 .setNetwork(info.getNetwork())
Yuyang Huangff963222023-06-01 18:42:42 +0900763 .setRemoveExpiredService(true)
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900764 .setIsPassiveMode(true);
765 if (typeAndSubtype.second != null) {
766 // The parsing ensures subtype starts with an underscore.
767 // MdnsSearchOptions expects the underscore to not be present.
768 optionsBuilder.addSubtype(typeAndSubtype.second.substring(1));
769 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900770 mMdnsDiscoveryManager.registerListener(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900771 listenServiceType, listener, optionsBuilder.build());
Paul Hud44e1b72023-06-16 02:07:42 +0000772 storeDiscoveryManagerRequestMap(clientRequestId, transactionId,
773 listener, clientInfo, info.getNetwork());
774 clientInfo.onDiscoverServicesStarted(clientRequestId, info);
775 clientInfo.log("Register a DiscoveryListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +0000776 + " for service type:" + listenServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700777 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800778 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000779 if (discoverServices(transactionId, info)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800780 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +0000781 Log.d(TAG, "Discover " + msg.arg2 + " " + transactionId
Paul Hu23fa2022023-01-13 22:57:24 +0800782 + info.getServiceType());
783 }
Paul Hud44e1b72023-06-16 02:07:42 +0000784 storeLegacyRequestMap(
785 clientRequestId, transactionId, clientInfo, msg.what);
786 clientInfo.onDiscoverServicesStarted(clientRequestId, info);
Paul Hu23fa2022023-01-13 22:57:24 +0800787 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000788 stopServiceDiscovery(transactionId);
789 clientInfo.onDiscoverServicesFailed(clientRequestId,
Paul Hu23fa2022023-01-13 22:57:24 +0800790 NsdManager.FAILURE_INTERNAL_ERROR);
791 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700792 }
793 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800794 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900795 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800796 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900797 args = (ListenerArgs) msg.obj;
798 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000799 // If the binder death notification for a INsdManagerCallback was received
800 // before any calls are received by NsdService, the clientInfo would be
801 // cleared and cause NPE. Add a null check here to prevent this corner case.
802 if (clientInfo == null) {
803 Log.e(TAG, "Unknown connector in stop discovery");
804 break;
805 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700806
Paul Hud44e1b72023-06-16 02:07:42 +0000807 final ClientRequest request =
808 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900809 if (request == null) {
810 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700811 break;
812 }
Paul Hud44e1b72023-06-16 02:07:42 +0000813 transactionId = request.mTransactionId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900814 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
815 // point, so this needs to check the type of the original request to
816 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900817 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +0000818 stopDiscoveryManagerRequest(
819 request, clientRequestId, transactionId, clientInfo);
820 clientInfo.onStopDiscoverySucceeded(clientRequestId);
821 clientInfo.log("Unregister the DiscoveryListener " + transactionId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700822 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000823 removeRequestMap(clientRequestId, transactionId, clientInfo);
824 if (stopServiceDiscovery(transactionId)) {
825 clientInfo.onStopDiscoverySucceeded(clientRequestId);
Paul Hu23fa2022023-01-13 22:57:24 +0800826 } else {
827 clientInfo.onStopDiscoveryFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000828 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu23fa2022023-01-13 22:57:24 +0800829 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700830 }
831 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900832 }
833 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800834 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900835 args = (ListenerArgs) msg.obj;
836 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000837 // If the binder death notification for a INsdManagerCallback was received
838 // before any calls are received by NsdService, the clientInfo would be
839 // cleared and cause NPE. Add a null check here to prevent this corner case.
840 if (clientInfo == null) {
841 Log.e(TAG, "Unknown connector in registration");
842 break;
843 }
844
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700845 if (requestLimitReached(clientInfo)) {
Paul Hu777ed052023-06-19 13:35:15 +0000846 clientInfo.onRegisterServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000847 clientRequestId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700848 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700849 }
850
Paul Hud44e1b72023-06-16 02:07:42 +0000851 transactionId = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900852 final NsdServiceInfo serviceInfo = args.serviceInfo;
853 final String serviceType = serviceInfo.getServiceType();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900854 final Pair<String, String> typeSubtype = parseTypeAndSubtype(serviceType);
855 final String registerServiceType = typeSubtype == null
856 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800857 if (clientInfo.mUseJavaBackend
858 || mDeps.isMdnsAdvertiserEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900859 || useAdvertiserForType(registerServiceType)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900860 if (registerServiceType == null) {
861 Log.e(TAG, "Invalid service type: " + serviceType);
Paul Hu777ed052023-06-19 13:35:15 +0000862 clientInfo.onRegisterServiceFailedImmediately(
863 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900864 break;
865 }
866 serviceInfo.setServiceType(registerServiceType);
867 serviceInfo.setServiceName(truncateServiceName(
868 serviceInfo.getServiceName()));
869
870 maybeStartMonitoringSockets();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900871 // TODO: pass in the subtype as well. Including the subtype in the
872 // service type would generate service instance names like
873 // Name._subtype._sub._type._tcp, which is incorrect
874 // (it should be Name._type._tcp).
Paul Hud44e1b72023-06-16 02:07:42 +0000875 mAdvertiser.addService(transactionId, serviceInfo, typeSubtype.second);
876 storeAdvertiserRequestMap(clientRequestId, transactionId, clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900877 serviceInfo.getNetwork());
Irfan Sheriff75006652012-04-17 23:15:29 -0700878 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900879 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000880 if (registerService(transactionId, serviceInfo)) {
881 if (DBG) {
882 Log.d(TAG, "Register " + clientRequestId
883 + " " + transactionId);
884 }
885 storeLegacyRequestMap(
886 clientRequestId, transactionId, clientInfo, msg.what);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900887 // Return success after mDns reports success
888 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000889 unregisterService(transactionId);
Paul Hu777ed052023-06-19 13:35:15 +0000890 clientInfo.onRegisterServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000891 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900892 }
893
Irfan Sheriff75006652012-04-17 23:15:29 -0700894 }
895 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900896 }
897 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800898 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900899 args = (ListenerArgs) msg.obj;
900 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000901 // If the binder death notification for a INsdManagerCallback was received
902 // before any calls are received by NsdService, the clientInfo would be
903 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900904 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800905 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700906 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700907 }
Paul Hud44e1b72023-06-16 02:07:42 +0000908 final ClientRequest request =
909 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900910 if (request == null) {
911 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
912 break;
913 }
Paul Hud44e1b72023-06-16 02:07:42 +0000914 transactionId = request.mTransactionId;
915 removeRequestMap(clientRequestId, transactionId, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900916
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900917 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
918 // so this needs to check the type of the original request to unregister
919 // instead of looking at the flag value.
920 if (request instanceof AdvertiserClientRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +0000921 mAdvertiser.removeService(transactionId);
Paul Hu777ed052023-06-19 13:35:15 +0000922 clientInfo.onUnregisterServiceSucceeded(clientRequestId, transactionId,
923 request.calculateRequestDurationMs());
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700924 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000925 if (unregisterService(transactionId)) {
Paul Hu777ed052023-06-19 13:35:15 +0000926 clientInfo.onUnregisterServiceSucceeded(clientRequestId,
927 transactionId, request.calculateRequestDurationMs());
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900928 } else {
929 clientInfo.onUnregisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000930 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900931 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700932 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700933 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900934 }
Paul Hu75069ed2023-01-14 00:31:09 +0800935 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800936 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900937 args = (ListenerArgs) msg.obj;
938 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000939 // If the binder death notification for a INsdManagerCallback was received
940 // before any calls are received by NsdService, the clientInfo would be
941 // cleared and cause NPE. Add a null check here to prevent this corner case.
942 if (clientInfo == null) {
943 Log.e(TAG, "Unknown connector in resolution");
944 break;
945 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700946
Paul Hu75069ed2023-01-14 00:31:09 +0800947 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000948 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900949 final Pair<String, String> typeSubtype =
950 parseTypeAndSubtype(info.getServiceType());
951 final String serviceType = typeSubtype == null
952 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800953 if (clientInfo.mUseJavaBackend
954 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900955 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800956 if (serviceType == null) {
Paul Hud44e1b72023-06-16 02:07:42 +0000957 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu75069ed2023-01-14 00:31:09 +0800958 NsdManager.FAILURE_INTERNAL_ERROR);
959 break;
960 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900961 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +0800962
963 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +0000964 final MdnsListener listener = new ResolutionListener(clientRequestId,
965 transactionId, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800966 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
967 .setNetwork(info.getNetwork())
968 .setIsPassiveMode(true)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900969 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +0900970 .setRemoveExpiredService(true)
Paul Hu75069ed2023-01-14 00:31:09 +0800971 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900972 mMdnsDiscoveryManager.registerListener(
973 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +0000974 storeDiscoveryManagerRequestMap(clientRequestId, transactionId,
975 listener, clientInfo, info.getNetwork());
976 clientInfo.log("Register a ResolutionListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +0000977 + " for service type:" + resolveServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700978 } else {
Paul Hu75069ed2023-01-14 00:31:09 +0800979 if (clientInfo.mResolvedService != null) {
980 clientInfo.onResolveServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000981 clientRequestId, NsdManager.FAILURE_ALREADY_ACTIVE);
Paul Hu75069ed2023-01-14 00:31:09 +0800982 break;
983 }
984
985 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000986 if (resolveService(transactionId, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800987 clientInfo.mResolvedService = new NsdServiceInfo();
Paul Hud44e1b72023-06-16 02:07:42 +0000988 storeLegacyRequestMap(
989 clientRequestId, transactionId, clientInfo, msg.what);
Paul Hu75069ed2023-01-14 00:31:09 +0800990 } else {
991 clientInfo.onResolveServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000992 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu75069ed2023-01-14 00:31:09 +0800993 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700994 }
995 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800996 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900997 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +0000998 if (DBG) Log.d(TAG, "Stop service resolution");
999 args = (ListenerArgs) msg.obj;
1000 clientInfo = mClients.get(args.connector);
1001 // If the binder death notification for a INsdManagerCallback was received
1002 // before any calls are received by NsdService, the clientInfo would be
1003 // cleared and cause NPE. Add a null check here to prevent this corner case.
1004 if (clientInfo == null) {
1005 Log.e(TAG, "Unknown connector in stop resolution");
1006 break;
1007 }
1008
Paul Hud44e1b72023-06-16 02:07:42 +00001009 final ClientRequest request =
1010 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001011 if (request == null) {
1012 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
1013 break;
1014 }
Paul Hud44e1b72023-06-16 02:07:42 +00001015 transactionId = request.mTransactionId;
Paul Hue4f5f252023-02-16 21:13:47 +08001016 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
1017 // point, so this needs to check the type of the original request to
1018 // unregister instead of looking at the flag value.
1019 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001020 stopDiscoveryManagerRequest(
1021 request, clientRequestId, transactionId, clientInfo);
1022 clientInfo.onStopResolutionSucceeded(clientRequestId);
1023 clientInfo.log("Unregister the ResolutionListener " + transactionId);
Paul Hub58deb72022-12-26 09:24:42 +00001024 } else {
Paul Hud44e1b72023-06-16 02:07:42 +00001025 removeRequestMap(clientRequestId, transactionId, clientInfo);
1026 if (stopResolveService(transactionId)) {
1027 clientInfo.onStopResolutionSucceeded(clientRequestId);
Paul Hue4f5f252023-02-16 21:13:47 +08001028 } else {
1029 clientInfo.onStopResolutionFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001030 clientRequestId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hue4f5f252023-02-16 21:13:47 +08001031 }
1032 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +00001033 }
Paul Hub58deb72022-12-26 09:24:42 +00001034 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001035 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001036 case NsdManager.REGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001037 if (DBG) Log.d(TAG, "Register a service callback");
1038 args = (ListenerArgs) msg.obj;
1039 clientInfo = mClients.get(args.connector);
1040 // If the binder death notification for a INsdManagerCallback was received
1041 // before any calls are received by NsdService, the clientInfo would be
1042 // cleared and cause NPE. Add a null check here to prevent this corner case.
1043 if (clientInfo == null) {
1044 Log.e(TAG, "Unknown connector in callback registration");
1045 break;
1046 }
1047
Paul Hu30bd70d2023-02-07 13:20:56 +00001048 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001049 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001050 final Pair<String, String> typeAndSubtype =
1051 parseTypeAndSubtype(info.getServiceType());
1052 final String serviceType = typeAndSubtype == null
1053 ? null : typeAndSubtype.first;
Paul Hu30bd70d2023-02-07 13:20:56 +00001054 if (serviceType == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001055 clientInfo.onServiceInfoCallbackRegistrationFailed(clientRequestId,
Paul Hu30bd70d2023-02-07 13:20:56 +00001056 NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +00001057 break;
1058 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001059 final String resolveServiceType = serviceType + ".local";
Paul Hu18aeccc2022-12-27 08:48:48 +00001060
Paul Hu30bd70d2023-02-07 13:20:56 +00001061 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001062 final MdnsListener listener = new ServiceInfoListener(clientRequestId,
1063 transactionId, info, resolveServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +00001064 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1065 .setNetwork(info.getNetwork())
1066 .setIsPassiveMode(true)
1067 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001068 .setRemoveExpiredService(true)
Paul Hu30bd70d2023-02-07 13:20:56 +00001069 .build();
1070 mMdnsDiscoveryManager.registerListener(
1071 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001072 storeDiscoveryManagerRequestMap(clientRequestId, transactionId, listener,
1073 clientInfo, info.getNetwork());
1074 clientInfo.log("Register a ServiceInfoListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001075 + " for service type:" + resolveServiceType);
Paul Hu18aeccc2022-12-27 08:48:48 +00001076 break;
Paul Hu30bd70d2023-02-07 13:20:56 +00001077 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001078 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001079 if (DBG) Log.d(TAG, "Unregister a service callback");
1080 args = (ListenerArgs) msg.obj;
1081 clientInfo = mClients.get(args.connector);
1082 // If the binder death notification for a INsdManagerCallback was received
1083 // before any calls are received by NsdService, the clientInfo would be
1084 // cleared and cause NPE. Add a null check here to prevent this corner case.
1085 if (clientInfo == null) {
1086 Log.e(TAG, "Unknown connector in callback unregistration");
1087 break;
1088 }
1089
Paul Hud44e1b72023-06-16 02:07:42 +00001090 final ClientRequest request =
1091 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001092 if (request == null) {
Paul Hu30bd70d2023-02-07 13:20:56 +00001093 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE_CALLBACK");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001094 break;
1095 }
Paul Hud44e1b72023-06-16 02:07:42 +00001096 transactionId = request.mTransactionId;
Paul Hu30bd70d2023-02-07 13:20:56 +00001097 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001098 stopDiscoveryManagerRequest(
1099 request, clientRequestId, transactionId, clientInfo);
1100 clientInfo.onServiceInfoCallbackUnregistered(clientRequestId);
1101 clientInfo.log("Unregister the ServiceInfoListener " + transactionId);
Paul Hu18aeccc2022-12-27 08:48:48 +00001102 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001103 loge("Unregister failed with non-DiscoveryManagerRequest.");
Paul Hu18aeccc2022-12-27 08:48:48 +00001104 }
Paul Hu18aeccc2022-12-27 08:48:48 +00001105 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001106 }
paulhu2b9ed952022-02-10 21:58:32 +08001107 case MDNS_SERVICE_EVENT:
1108 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +09001109 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001110 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001111 break;
Paul Hu019621e2023-01-13 23:26:49 +08001112 case MDNS_DISCOVERY_MANAGER_EVENT:
1113 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
1114 return NOT_HANDLED;
1115 }
1116 break;
Irfan Sheriff75006652012-04-17 23:15:29 -07001117 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001118 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001119 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001120 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001121 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001122
Paul Hud44e1b72023-06-16 02:07:42 +00001123 private boolean handleMDnsServiceEvent(int code, int transactionId, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001124 NsdServiceInfo servInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001125 ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001126 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001127 Log.e(TAG, String.format(
1128 "transactionId %d for %d has no client mapping", transactionId, code));
Hugo Benichif0c84092017-04-05 14:43:29 +09001129 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001130 }
1131
1132 /* This goes in response as msg.arg2 */
Paul Hud44e1b72023-06-16 02:07:42 +00001133 int clientRequestId = clientInfo.getClientRequestId(transactionId);
1134 if (clientRequestId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -07001135 // This can happen because of race conditions. For example,
1136 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
1137 // and we may get in this situation.
Paul Hud44e1b72023-06-16 02:07:42 +00001138 Log.d(TAG, String.format("%d for transactionId %d that is no longer active",
1139 code, transactionId));
Hugo Benichif0c84092017-04-05 14:43:29 +09001140 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001141 }
Hugo Benichi32be63d2017-04-05 14:06:11 +09001142 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00001143 Log.d(TAG, String.format(
1144 "MDns service event code:%d transactionId=%d", code, transactionId));
Hugo Benichi32be63d2017-04-05 14:06:11 +09001145 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001146 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +08001147 case IMDnsEventListener.SERVICE_FOUND: {
1148 final DiscoveryInfo info = (DiscoveryInfo) obj;
1149 final String name = info.serviceName;
1150 final String type = info.registrationType;
1151 servInfo = new NsdServiceInfo(name, type);
1152 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001153 if (foundNetId == 0L) {
1154 // Ignore services that do not have a Network: they are not usable
1155 // by apps, as they would need privileged permissions to use
1156 // interfaces that do not have an associated Network.
1157 break;
1158 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +09001159 if (foundNetId == INetd.DUMMY_NET_ID) {
1160 // Ignore services on the dummy0 interface: they are only seen when
1161 // discovering locally advertised services, and are not reachable
1162 // through that interface.
1163 break;
1164 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001165 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Paul Hud44e1b72023-06-16 02:07:42 +00001166 clientInfo.onServiceFound(clientRequestId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001167 break;
paulhu2b9ed952022-02-10 21:58:32 +08001168 }
1169 case IMDnsEventListener.SERVICE_LOST: {
1170 final DiscoveryInfo info = (DiscoveryInfo) obj;
1171 final String name = info.serviceName;
1172 final String type = info.registrationType;
1173 final int lostNetId = info.netId;
1174 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001175 // The network could be set to null (netId 0) if it was torn down when the
1176 // service is lost
1177 // TODO: avoid returning null in that case, possibly by remembering
1178 // found services on the same interface index and their network at the time
1179 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Paul Hud44e1b72023-06-16 02:07:42 +00001180 clientInfo.onServiceLost(clientRequestId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001181 break;
paulhu2b9ed952022-02-10 21:58:32 +08001182 }
1183 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001184 clientInfo.onDiscoverServicesFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001185 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001186 break;
paulhu2b9ed952022-02-10 21:58:32 +08001187 case IMDnsEventListener.SERVICE_REGISTERED: {
1188 final RegistrationInfo info = (RegistrationInfo) obj;
1189 final String name = info.serviceName;
1190 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Paul Hu777ed052023-06-19 13:35:15 +00001191 final ClientRequest request =
1192 clientInfo.mClientRequests.get(clientRequestId);
1193 clientInfo.onRegisterServiceSucceeded(clientRequestId, servInfo,
1194 transactionId, request.calculateRequestDurationMs());
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001195 break;
paulhu2b9ed952022-02-10 21:58:32 +08001196 }
1197 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Paul Hu777ed052023-06-19 13:35:15 +00001198 final ClientRequest request =
1199 clientInfo.mClientRequests.get(clientRequestId);
1200 clientInfo.onRegisterServiceFailed(clientRequestId,
1201 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1202 request.calculateRequestDurationMs());
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001203 break;
paulhu2b9ed952022-02-10 21:58:32 +08001204 case IMDnsEventListener.SERVICE_RESOLVED: {
1205 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001206 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +08001207 final String fullName = info.serviceFullName;
1208 while (index < fullName.length() && fullName.charAt(index) != '.') {
1209 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001210 ++index;
1211 }
1212 ++index;
1213 }
paulhu2b9ed952022-02-10 21:58:32 +08001214 if (index >= fullName.length()) {
1215 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001216 break;
1217 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001218
paulhube186602022-04-12 07:18:23 +00001219 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001220 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001221 String type = rest.replace(".local.", "");
1222
Paul Hu30bd70d2023-02-07 13:20:56 +00001223 final NsdServiceInfo serviceInfo = clientInfo.mResolvedService;
Paul Hu18aeccc2022-12-27 08:48:48 +00001224 serviceInfo.setServiceName(name);
1225 serviceInfo.setServiceType(type);
1226 serviceInfo.setPort(info.port);
1227 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001228 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001229
Paul Hud44e1b72023-06-16 02:07:42 +00001230 stopResolveService(transactionId);
1231 removeRequestMap(clientRequestId, transactionId, clientInfo);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001232
Paul Hud44e1b72023-06-16 02:07:42 +00001233 final int transactionId2 = getUniqueId();
1234 if (getAddrInfo(transactionId2, info.hostname, info.interfaceIdx)) {
1235 storeLegacyRequestMap(clientRequestId, transactionId2, clientInfo,
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001236 NsdManager.RESOLVE_SERVICE);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001237 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001238 clientInfo.onResolveServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001239 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu30bd70d2023-02-07 13:20:56 +00001240 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001241 }
1242 break;
paulhu2b9ed952022-02-10 21:58:32 +08001243 }
1244 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001245 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001246 stopResolveService(transactionId);
1247 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001248 clientInfo.onResolveServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001249 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu30bd70d2023-02-07 13:20:56 +00001250 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001251 break;
paulhu2b9ed952022-02-10 21:58:32 +08001252 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001253 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001254 stopGetAddrInfo(transactionId);
1255 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001256 clientInfo.onResolveServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001257 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu30bd70d2023-02-07 13:20:56 +00001258 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001259 break;
paulhu2b9ed952022-02-10 21:58:32 +08001260 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001261 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001262 final GetAddressInfo info = (GetAddressInfo) obj;
1263 final String address = info.address;
1264 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001265 InetAddress serviceHost = null;
1266 try {
paulhu2b9ed952022-02-10 21:58:32 +08001267 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001268 } catch (UnknownHostException e) {
1269 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1270 }
1271
1272 // If the resolved service is on an interface without a network, consider it
1273 // as a failure: it would not be usable by apps as they would need
1274 // privileged permissions.
Paul Hu30bd70d2023-02-07 13:20:56 +00001275 if (netId != NETID_UNSET && serviceHost != null) {
1276 clientInfo.mResolvedService.setHost(serviceHost);
1277 setServiceNetworkForCallback(clientInfo.mResolvedService,
1278 netId, info.interfaceIdx);
1279 clientInfo.onResolveServiceSucceeded(
Paul Hud44e1b72023-06-16 02:07:42 +00001280 clientRequestId, clientInfo.mResolvedService);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001281 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001282 clientInfo.onResolveServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001283 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001284 }
Paul Hud44e1b72023-06-16 02:07:42 +00001285 stopGetAddrInfo(transactionId);
1286 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001287 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001288 break;
paulhu2b9ed952022-02-10 21:58:32 +08001289 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001290 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001291 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001292 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001293 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001294 }
Paul Hu019621e2023-01-13 23:26:49 +08001295
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001296 @Nullable
1297 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(
1298 final MdnsEvent event, int code) {
Paul Hu019621e2023-01-13 23:26:49 +08001299 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001300 final String[] typeArray = serviceInfo.getServiceType();
1301 final String joinedType;
1302 if (typeArray.length == 0
1303 || !typeArray[typeArray.length - 1].equals(LOCAL_DOMAIN_NAME)) {
1304 Log.wtf(TAG, "MdnsServiceInfo type does not end in .local: "
1305 + Arrays.toString(typeArray));
1306 return null;
1307 } else {
1308 joinedType = TextUtils.join(".",
1309 Arrays.copyOfRange(typeArray, 0, typeArray.length - 1));
1310 }
1311 final String serviceType;
1312 switch (code) {
1313 case NsdManager.SERVICE_FOUND:
1314 case NsdManager.SERVICE_LOST:
1315 // For consistency with historical behavior, discovered service types have
1316 // a dot at the end.
1317 serviceType = joinedType + ".";
1318 break;
1319 case RESOLVE_SERVICE_SUCCEEDED:
1320 // For consistency with historical behavior, resolved service types have
1321 // a dot at the beginning.
1322 serviceType = "." + joinedType;
1323 break;
1324 default:
1325 serviceType = joinedType;
1326 break;
1327 }
Paul Hu019621e2023-01-13 23:26:49 +08001328 final String serviceName = serviceInfo.getServiceInstanceName();
1329 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1330 final Network network = serviceInfo.getNetwork();
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001331 // In MdnsDiscoveryManagerEvent, the Network can be null which means it is a
1332 // network for Tethering interface. In other words, the network == null means the
1333 // network has netId = INetd.LOCAL_NET_ID.
Paul Hu019621e2023-01-13 23:26:49 +08001334 setServiceNetworkForCallback(
1335 servInfo,
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001336 network == null ? INetd.LOCAL_NET_ID : network.netId,
Paul Hu019621e2023-01-13 23:26:49 +08001337 serviceInfo.getInterfaceIndex());
1338 return servInfo;
1339 }
1340
1341 private boolean handleMdnsDiscoveryManagerEvent(
1342 int transactionId, int code, Object obj) {
Paul Hud44e1b72023-06-16 02:07:42 +00001343 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Paul Hu019621e2023-01-13 23:26:49 +08001344 if (clientInfo == null) {
1345 Log.e(TAG, String.format(
1346 "id %d for %d has no client mapping", transactionId, code));
1347 return false;
1348 }
1349
1350 final MdnsEvent event = (MdnsEvent) obj;
Paul Hud44e1b72023-06-16 02:07:42 +00001351 final int clientRequestId = event.mClientRequestId;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001352 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event, code);
1353 // Errors are already logged if null
1354 if (info == null) return false;
Paul Hu83ec7f42023-06-07 18:04:09 +08001355 mServiceLogs.log(String.format(
1356 "MdnsDiscoveryManager event code=%s transactionId=%d",
1357 NsdManager.nameOf(code), transactionId));
Paul Hu019621e2023-01-13 23:26:49 +08001358 switch (code) {
1359 case NsdManager.SERVICE_FOUND:
Paul Hud44e1b72023-06-16 02:07:42 +00001360 clientInfo.onServiceFound(clientRequestId, info);
Paul Hu319751a2023-01-13 23:56:34 +08001361 break;
1362 case NsdManager.SERVICE_LOST:
Paul Hud44e1b72023-06-16 02:07:42 +00001363 clientInfo.onServiceLost(clientRequestId, info);
Paul Hu019621e2023-01-13 23:26:49 +08001364 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001365 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
Paul Hud44e1b72023-06-16 02:07:42 +00001366 final ClientRequest request =
1367 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001368 if (request == null) {
1369 Log.e(TAG, "Unknown client request in RESOLVE_SERVICE_SUCCEEDED");
1370 break;
1371 }
Paul Hu75069ed2023-01-14 00:31:09 +08001372 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Paul Hu75069ed2023-01-14 00:31:09 +08001373 info.setPort(serviceInfo.getPort());
1374
1375 Map<String, String> attrs = serviceInfo.getAttributes();
1376 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1377 final String key = kv.getKey();
1378 try {
1379 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1380 } catch (IllegalArgumentException e) {
1381 Log.e(TAG, "Invalid attribute", e);
1382 }
1383 }
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001384 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu2b865912023-03-06 14:27:53 +08001385 if (addresses.size() != 0) {
1386 info.setHostAddresses(addresses);
Paul Hud44e1b72023-06-16 02:07:42 +00001387 clientInfo.onResolveServiceSucceeded(clientRequestId, info);
Paul Hu2b865912023-03-06 14:27:53 +08001388 } else {
1389 // No address. Notify resolution failure.
Paul Hu75069ed2023-01-14 00:31:09 +08001390 clientInfo.onResolveServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001391 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu75069ed2023-01-14 00:31:09 +08001392 }
1393
1394 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001395 if (!(request instanceof DiscoveryManagerRequest)) {
1396 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1397 break;
1398 }
Paul Hud44e1b72023-06-16 02:07:42 +00001399 stopDiscoveryManagerRequest(
1400 request, clientRequestId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001401 break;
1402 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001403 case NsdManager.SERVICE_UPDATED: {
1404 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1405 info.setPort(serviceInfo.getPort());
1406
1407 Map<String, String> attrs = serviceInfo.getAttributes();
1408 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1409 final String key = kv.getKey();
1410 try {
1411 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1412 } catch (IllegalArgumentException e) {
1413 Log.e(TAG, "Invalid attribute", e);
1414 }
1415 }
1416
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001417 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001418 info.setHostAddresses(addresses);
Paul Hud44e1b72023-06-16 02:07:42 +00001419 clientInfo.onServiceUpdated(clientRequestId, info);
Paul Hu30bd70d2023-02-07 13:20:56 +00001420 break;
1421 }
1422 case NsdManager.SERVICE_UPDATED_LOST:
Paul Hud44e1b72023-06-16 02:07:42 +00001423 clientInfo.onServiceUpdatedLost(clientRequestId);
Paul Hu30bd70d2023-02-07 13:20:56 +00001424 break;
Paul Hu019621e2023-01-13 23:26:49 +08001425 default:
1426 return false;
1427 }
1428 return true;
1429 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001430 }
1431 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001432
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001433 @NonNull
1434 private static List<InetAddress> getInetAddresses(@NonNull MdnsServiceInfo serviceInfo) {
1435 final List<String> v4Addrs = serviceInfo.getIpv4Addresses();
1436 final List<String> v6Addrs = serviceInfo.getIpv6Addresses();
1437 final List<InetAddress> addresses = new ArrayList<>(v4Addrs.size() + v6Addrs.size());
1438 for (String ipv4Address : v4Addrs) {
1439 try {
1440 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1441 } catch (IllegalArgumentException e) {
1442 Log.wtf(TAG, "Invalid ipv4 address", e);
1443 }
1444 }
1445 for (String ipv6Address : v6Addrs) {
1446 try {
Yuyang Huanga6a6ff92023-04-24 13:33:34 +09001447 final Inet6Address addr = (Inet6Address) InetAddresses.parseNumericAddress(
1448 ipv6Address);
1449 addresses.add(InetAddressUtils.withScopeId(addr, serviceInfo.getInterfaceIndex()));
1450 } catch (IllegalArgumentException e) {
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001451 Log.wtf(TAG, "Invalid ipv6 address", e);
1452 }
1453 }
1454 return addresses;
1455 }
1456
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001457 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1458 switch (netId) {
1459 case NETID_UNSET:
1460 info.setNetwork(null);
1461 break;
1462 case INetd.LOCAL_NET_ID:
1463 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1464 // visible / usable for apps, so do not return it. Store the interface
1465 // index instead, so at least if the client tries to resolve the service
1466 // with that NsdServiceInfo, it will be done on the same interface.
1467 // If they recreate the NsdServiceInfo themselves, resolution would be
1468 // done on all interfaces as before T, which should also work.
1469 info.setNetwork(null);
1470 info.setInterfaceIndex(ifaceIdx);
1471 break;
1472 default:
1473 info.setNetwork(new Network(netId));
1474 }
1475 }
1476
paulhube186602022-04-12 07:18:23 +00001477 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1478 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1479 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1480 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1481 private String unescape(String s) {
1482 StringBuilder sb = new StringBuilder(s.length());
1483 for (int i = 0; i < s.length(); ++i) {
1484 char c = s.charAt(i);
1485 if (c == '\\') {
1486 if (++i >= s.length()) {
1487 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1488 break;
1489 }
1490 c = s.charAt(i);
1491 if (c != '.' && c != '\\') {
1492 if (i + 2 >= s.length()) {
1493 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1494 break;
1495 }
1496 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1497 + (s.charAt(i + 2) - '0'));
1498 i += 2;
1499 }
1500 }
1501 sb.append(c);
1502 }
1503 return sb.toString();
1504 }
1505
Paul Hu7445e3d2023-03-03 15:14:00 +08001506 /**
1507 * Check the given service type is valid and construct it to a service type
1508 * which can use for discovery / resolution service.
1509 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001510 * <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 +08001511 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1512 * underscore; they are alphanumerical characters or dashes or underscore, except the
1513 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1514 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001515 * <p>The subtype may also be specified with a comma after the service type, for example
1516 * _type._tcp,_subtype.
1517 *
Paul Hu7445e3d2023-03-03 15:14:00 +08001518 * @param serviceType the request service type for discovery / resolution service
1519 * @return constructed service type or null if the given service type is invalid.
1520 */
1521 @Nullable
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001522 public static Pair<String, String> parseTypeAndSubtype(String serviceType) {
Paul Hu7445e3d2023-03-03 15:14:00 +08001523 if (TextUtils.isEmpty(serviceType)) return null;
1524
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001525 final String typeOrSubtypePattern = "_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]";
Paul Hu7445e3d2023-03-03 15:14:00 +08001526 final Pattern serviceTypePattern = Pattern.compile(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001527 // Optional leading subtype (_subtype._type._tcp)
1528 // (?: xxx) is a non-capturing parenthesis, don't capture the dot
1529 "^(?:(" + typeOrSubtypePattern + ")\\.)?"
1530 // Actual type (_type._tcp.local)
1531 + "(" + typeOrSubtypePattern + "\\._(?:tcp|udp))"
Paul Hu7445e3d2023-03-03 15:14:00 +08001532 // Drop '.' at the end of service type that is compatible with old backend.
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001533 // e.g. allow "_type._tcp.local."
1534 + "\\.?"
1535 // Optional subtype after comma, for "_type._tcp,_subtype" format
1536 + "(?:,(" + typeOrSubtypePattern + "))?"
1537 + "$");
Paul Hu7445e3d2023-03-03 15:14:00 +08001538 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1539 if (!matcher.matches()) return null;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001540 // Use the subtype either at the beginning or after the comma
1541 final String subtype = matcher.group(1) != null ? matcher.group(1) : matcher.group(3);
1542 return new Pair<>(matcher.group(2), subtype);
Paul Hu7445e3d2023-03-03 15:14:00 +08001543 }
1544
Hugo Benichi803a2f02017-04-24 11:35:06 +09001545 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001546 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001547 this(ctx, handler, cleanupDelayMs, new Dependencies());
1548 }
1549
1550 @VisibleForTesting
1551 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001552 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001553 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001554 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001555 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001556 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1557 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001558 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001559
Paul Hu14667de2023-04-17 22:42:47 +08001560 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper(),
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001561 LOGGER.forSubComponent("MdnsSocketProvider"), new SocketRequestMonitor());
Yuyang Huang700778b2023-03-08 16:17:05 +09001562 // Netlink monitor starts on boot, and intentionally never stopped, to ensure that all
1563 // address events are received.
1564 handler.post(mMdnsSocketProvider::startNetLinkMonitor);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001565
1566 // NsdService is started after ActivityManager (startOtherServices in SystemServer, vs.
1567 // startBootstrapServices).
1568 mRunningAppActiveImportanceCutoff = mDeps.getDeviceConfigInt(
1569 MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF,
1570 DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF);
1571 final ActivityManager am = ctx.getSystemService(ActivityManager.class);
1572 am.addOnUidImportanceListener(new UidImportanceListener(handler),
1573 mRunningAppActiveImportanceCutoff);
1574
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001575 mMdnsSocketClient =
1576 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider);
Paul Hu14667de2023-04-17 22:42:47 +08001577 mMdnsDiscoveryManager = deps.makeMdnsDiscoveryManager(new ExecutorProvider(),
Yuyang Huang243d1a52023-05-23 17:26:52 +09001578 mMdnsSocketClient, LOGGER.forSubComponent("MdnsDiscoveryManager"));
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001579 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1580 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
Paul Hu14667de2023-04-17 22:42:47 +08001581 new AdvertiserCallback(), LOGGER.forSubComponent("MdnsAdvertiser"));
Paul Hu777ed052023-06-19 13:35:15 +00001582 mClock = deps.makeClock();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001583 }
1584
1585 /**
1586 * Dependencies of NsdService, for injection in tests.
1587 */
1588 @VisibleForTesting
1589 public static class Dependencies {
1590 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001591 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001592 *
1593 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001594 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001595 */
1596 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi278db582023-04-21 12:35:22 +09001597 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1598 MDNS_DISCOVERY_MANAGER_VERSION, DeviceConfigUtils.TETHERING_MODULE_NAME,
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +09001599 false /* defaultEnabled */);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001600 }
1601
1602 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001603 * Check whether the MdnsAdvertiser feature is enabled.
1604 *
1605 * @param context The global context information about an app environment.
1606 * @return true if the MdnsAdvertiser feature is enabled.
1607 */
1608 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi278db582023-04-21 12:35:22 +09001609 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1610 MDNS_ADVERTISER_VERSION, DeviceConfigUtils.TETHERING_MODULE_NAME,
1611 false /* defaultEnabled */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001612 }
1613
1614 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001615 * Get the type allowlist flag value.
1616 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1617 */
1618 @Nullable
1619 public String getTypeAllowlistFlags() {
1620 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1621 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1622 }
1623
1624 /**
1625 * @see DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)
1626 */
1627 public boolean isFeatureEnabled(Context context, String feature) {
1628 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1629 feature, DeviceConfigUtils.TETHERING_MODULE_NAME, false /* defaultEnabled */);
1630 }
1631
1632 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001633 * @see MdnsDiscoveryManager
1634 */
1635 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
Paul Hu14667de2023-04-17 22:42:47 +08001636 @NonNull ExecutorProvider executorProvider,
Yuyang Huang243d1a52023-05-23 17:26:52 +09001637 @NonNull MdnsMultinetworkSocketClient socketClient, @NonNull SharedLog sharedLog) {
1638 return new MdnsDiscoveryManager(executorProvider, socketClient, sharedLog);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001639 }
1640
1641 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001642 * @see MdnsAdvertiser
1643 */
1644 public MdnsAdvertiser makeMdnsAdvertiser(
1645 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
Paul Hu14667de2023-04-17 22:42:47 +08001646 @NonNull MdnsAdvertiser.AdvertiserCallback cb, @NonNull SharedLog sharedLog) {
1647 return new MdnsAdvertiser(looper, socketProvider, cb, sharedLog);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001648 }
1649
1650 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001651 * @see MdnsSocketProvider
1652 */
Paul Hu14667de2023-04-17 22:42:47 +08001653 public MdnsSocketProvider makeMdnsSocketProvider(@NonNull Context context,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001654 @NonNull Looper looper, @NonNull SharedLog sharedLog,
1655 @NonNull MdnsSocketProvider.SocketRequestMonitor socketCreationCallback) {
1656 return new MdnsSocketProvider(context, looper, sharedLog, socketCreationCallback);
1657 }
1658
1659 /**
1660 * @see DeviceConfig#getInt(String, String, int)
1661 */
1662 public int getDeviceConfigInt(@NonNull String config, int defaultValue) {
1663 return DeviceConfig.getInt(NAMESPACE_TETHERING, config, defaultValue);
1664 }
1665
1666 /**
1667 * @see Binder#getCallingUid()
1668 */
1669 public int getCallingUid() {
1670 return Binder.getCallingUid();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001671 }
Paul Hu777ed052023-06-19 13:35:15 +00001672
1673 /**
1674 * @see NetworkNsdReportedMetrics
1675 */
1676 public NetworkNsdReportedMetrics makeNetworkNsdReportedMetrics(
1677 boolean isLegacy, int clientId) {
1678 return new NetworkNsdReportedMetrics(isLegacy, clientId);
1679 }
1680
1681 /**
1682 * @see MdnsUtils.Clock
1683 */
1684 public Clock makeClock() {
1685 return new Clock();
1686 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001687 }
1688
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001689 /**
1690 * Return whether a type is allowlisted to use the Java backend.
1691 * @param type The service type
1692 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1693 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1694 */
1695 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1696 @NonNull String flagPrefix) {
1697 if (type == null) return false;
1698 final String typesConfig = mDeps.getTypeAllowlistFlags();
1699 if (TextUtils.isEmpty(typesConfig)) return false;
1700
1701 final String mappingPrefix = type + ":";
1702 String mappedFlag = null;
1703 for (String mapping : TextUtils.split(typesConfig, ",")) {
1704 if (mapping.startsWith(mappingPrefix)) {
1705 mappedFlag = mapping.substring(mappingPrefix.length());
1706 break;
1707 }
1708 }
1709
1710 if (mappedFlag == null) return false;
1711
1712 return mDeps.isFeatureEnabled(mContext,
1713 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1714 }
1715
1716 private boolean useDiscoveryManagerForType(@Nullable String type) {
1717 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1718 }
1719
1720 private boolean useAdvertiserForType(@Nullable String type) {
1721 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1722 }
1723
paulhu1b35e822022-04-08 14:48:41 +08001724 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001725 HandlerThread thread = new HandlerThread(TAG);
1726 thread.start();
1727 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001728 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001729 return service;
1730 }
1731
paulhu2b9ed952022-02-10 21:58:32 +08001732 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1733 private final StateMachine mStateMachine;
1734
1735 MDnsEventCallback(StateMachine sm) {
1736 mStateMachine = sm;
1737 }
1738
1739 @Override
1740 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1741 mStateMachine.sendMessage(
1742 MDNS_SERVICE_EVENT, status.result, status.id, status);
1743 }
1744
1745 @Override
1746 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1747 mStateMachine.sendMessage(
1748 MDNS_SERVICE_EVENT, status.result, status.id, status);
1749 }
1750
1751 @Override
1752 public void onServiceResolutionStatus(final ResolutionInfo status) {
1753 mStateMachine.sendMessage(
1754 MDNS_SERVICE_EVENT, status.result, status.id, status);
1755 }
1756
1757 @Override
1758 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1759 mStateMachine.sendMessage(
1760 MDNS_SERVICE_EVENT, status.result, status.id, status);
1761 }
1762
1763 @Override
1764 public int getInterfaceVersion() throws RemoteException {
1765 return this.VERSION;
1766 }
1767
1768 @Override
1769 public String getInterfaceHash() throws RemoteException {
1770 return this.HASH;
1771 }
1772 }
1773
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001774 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
1775 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001776 public void onRegisterServiceSucceeded(int transactionId, NsdServiceInfo registeredInfo) {
1777 mServiceLogs.log("onRegisterServiceSucceeded: transactionId " + transactionId);
1778 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001779 if (clientInfo == null) return;
1780
Paul Hud44e1b72023-06-16 02:07:42 +00001781 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1782 if (clientRequestId < 0) return;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001783
1784 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1785 // historical behavior.
1786 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
Paul Hu777ed052023-06-19 13:35:15 +00001787 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1788 clientInfo.onRegisterServiceSucceeded(
1789 clientRequestId, cbInfo, transactionId, request.calculateRequestDurationMs());
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001790 }
1791
1792 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001793 public void onRegisterServiceFailed(int transactionId, int errorCode) {
1794 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001795 if (clientInfo == null) return;
1796
Paul Hud44e1b72023-06-16 02:07:42 +00001797 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1798 if (clientRequestId < 0) return;
Paul Hu777ed052023-06-19 13:35:15 +00001799 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1800 clientInfo.onRegisterServiceFailed(clientRequestId, errorCode, transactionId,
1801 request.calculateRequestDurationMs());
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001802 }
1803
Paul Hud44e1b72023-06-16 02:07:42 +00001804 private ClientInfo getClientInfoOrLog(int transactionId) {
1805 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001806 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001807 Log.e(TAG, String.format("Callback for service %d has no client", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001808 }
1809 return clientInfo;
1810 }
1811
Paul Hud44e1b72023-06-16 02:07:42 +00001812 private int getClientRequestIdOrLog(@NonNull ClientInfo info, int transactionId) {
1813 final int clientRequestId = info.getClientRequestId(transactionId);
1814 if (clientRequestId < 0) {
1815 Log.e(TAG, String.format(
1816 "Client request ID not found for service %d", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001817 }
Paul Hud44e1b72023-06-16 02:07:42 +00001818 return clientRequestId;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001819 }
1820 }
1821
Paul Hu2e0a88c2023-03-09 16:05:01 +08001822 private static class ConnectorArgs {
1823 @NonNull public final NsdServiceConnector connector;
1824 @NonNull public final INsdManagerCallback callback;
1825 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001826 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001827
1828 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00001829 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08001830 this.connector = connector;
1831 this.callback = callback;
1832 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001833 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001834 }
1835 }
1836
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001837 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08001838 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001839 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu2e0a88c2023-03-09 16:05:01 +08001840 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001841 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00001842 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
1843 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001844 mDeps.getCallingUid())));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001845 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07001846 }
1847
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001848 private static class ListenerArgs {
1849 public final NsdServiceConnector connector;
1850 public final NsdServiceInfo serviceInfo;
1851 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
1852 this.connector = connector;
1853 this.serviceInfo = serviceInfo;
1854 }
1855 }
1856
1857 private class NsdServiceConnector extends INsdServiceConnector.Stub
1858 implements IBinder.DeathRecipient {
1859 @Override
1860 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
1861 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1862 NsdManager.REGISTER_SERVICE, 0, listenerKey,
1863 new ListenerArgs(this, serviceInfo)));
1864 }
1865
1866 @Override
1867 public void unregisterService(int listenerKey) {
1868 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1869 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
1870 new ListenerArgs(this, null)));
1871 }
1872
1873 @Override
1874 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
1875 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1876 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
1877 new ListenerArgs(this, serviceInfo)));
1878 }
1879
1880 @Override
1881 public void stopDiscovery(int listenerKey) {
1882 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1883 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
1884 }
1885
1886 @Override
1887 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
1888 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1889 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
1890 new ListenerArgs(this, serviceInfo)));
1891 }
1892
1893 @Override
Paul Hub58deb72022-12-26 09:24:42 +00001894 public void stopResolution(int listenerKey) {
1895 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1896 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
1897 }
1898
1899 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00001900 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
1901 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1902 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
1903 new ListenerArgs(this, serviceInfo)));
1904 }
1905
1906 @Override
1907 public void unregisterServiceInfoCallback(int listenerKey) {
1908 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1909 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
1910 new ListenerArgs(this, null)));
1911 }
1912
1913 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001914 public void startDaemon() {
1915 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1916 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
1917 }
1918
1919 @Override
1920 public void binderDied() {
1921 mNsdStateMachine.sendMessage(
1922 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
1923 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001924 }
1925
Hugo Benichi912db992017-04-24 16:41:03 +09001926 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07001927 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07001928 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09001929 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
1930 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07001931 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07001932 }
1933
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001934 private int getUniqueId() {
1935 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
1936 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001937 }
1938
Paul Hud44e1b72023-06-16 02:07:42 +00001939 private boolean registerService(int transactionId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09001940 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00001941 Log.d(TAG, "registerService: " + transactionId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001942 }
Hugo Benichi6d706442017-04-24 16:19:58 +09001943 String name = service.getServiceName();
1944 String type = service.getServiceType();
1945 int port = service.getPort();
1946 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001947 final int registerInterface = getNetworkInterfaceIndex(service);
1948 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08001949 Log.e(TAG, "Interface to register service on not found");
1950 return false;
1951 }
Paul Hud44e1b72023-06-16 02:07:42 +00001952 return mMDnsManager.registerService(
1953 transactionId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001954 }
1955
Paul Hud44e1b72023-06-16 02:07:42 +00001956 private boolean unregisterService(int transactionId) {
1957 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001958 }
1959
Paul Hud44e1b72023-06-16 02:07:42 +00001960 private boolean discoverServices(int transactionId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08001961 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001962 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
1963 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001964 Log.e(TAG, "Interface to discover service on not found");
1965 return false;
1966 }
Paul Hud44e1b72023-06-16 02:07:42 +00001967 return mMDnsManager.discover(transactionId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001968 }
1969
Paul Hud44e1b72023-06-16 02:07:42 +00001970 private boolean stopServiceDiscovery(int transactionId) {
1971 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001972 }
1973
Paul Hud44e1b72023-06-16 02:07:42 +00001974 private boolean resolveService(int transactionId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001975 final String name = service.getServiceName();
1976 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001977 final int resolveInterface = getNetworkInterfaceIndex(service);
1978 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001979 Log.e(TAG, "Interface to resolve service on not found");
1980 return false;
1981 }
Paul Hud44e1b72023-06-16 02:07:42 +00001982 return mMDnsManager.resolve(transactionId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001983 }
1984
1985 /**
1986 * Guess the interface to use to resolve or discover a service on a specific network.
1987 *
1988 * This is an imperfect guess, as for example the network may be gone or not yet fully
1989 * registered. This is fine as failing is correct if the network is gone, and a client
1990 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
1991 * this is to support the legacy mdnsresponder implementation, which historically resolved
1992 * services on an unspecified network.
1993 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001994 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
1995 final Network network = serviceInfo.getNetwork();
1996 if (network == null) {
1997 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
1998 // provided by NsdService from discovery results, and the service was found on an
1999 // interface that has no app-usable Network).
2000 if (serviceInfo.getInterfaceIndex() != 0) {
2001 return serviceInfo.getInterfaceIndex();
2002 }
2003 return IFACE_IDX_ANY;
2004 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002005
2006 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
2007 if (cm == null) {
2008 Log.wtf(TAG, "No ConnectivityManager for resolveService");
2009 return IFACE_IDX_ANY;
2010 }
2011 final LinkProperties lp = cm.getLinkProperties(network);
2012 if (lp == null) return IFACE_IDX_ANY;
2013
2014 // Only resolve on non-stacked interfaces
2015 final NetworkInterface iface;
2016 try {
2017 iface = NetworkInterface.getByName(lp.getInterfaceName());
2018 } catch (SocketException e) {
2019 Log.e(TAG, "Error querying interface", e);
2020 return IFACE_IDX_ANY;
2021 }
2022
2023 if (iface == null) {
2024 Log.e(TAG, "Interface not found: " + lp.getInterfaceName());
2025 return IFACE_IDX_ANY;
2026 }
2027
2028 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002029 }
2030
Paul Hud44e1b72023-06-16 02:07:42 +00002031 private boolean stopResolveService(int transactionId) {
2032 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002033 }
2034
Paul Hud44e1b72023-06-16 02:07:42 +00002035 private boolean getAddrInfo(int transactionId, String hostname, int interfaceIdx) {
2036 return mMDnsManager.getServiceAddress(transactionId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002037 }
2038
Paul Hud44e1b72023-06-16 02:07:42 +00002039 private boolean stopGetAddrInfo(int transactionId) {
2040 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002041 }
2042
2043 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00002044 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2045 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002046
Paul Hub2e67d32023-04-18 05:50:14 +00002047 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2048 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07002049 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00002050
2051 // Dump service and clients logs
2052 pw.println();
Paul Hu14667de2023-04-17 22:42:47 +08002053 pw.println("Logs:");
Paul Hub2e67d32023-04-18 05:50:14 +00002054 pw.increaseIndent();
2055 mServiceLogs.reverseDump(pw);
2056 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002057 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002058
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002059 private abstract static class ClientRequest {
Paul Hud44e1b72023-06-16 02:07:42 +00002060 private final int mTransactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002061 private final Clock mClock;
2062 private final long mStartTimeMs;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002063
Paul Hu777ed052023-06-19 13:35:15 +00002064 private ClientRequest(int transactionId, @NonNull Clock clock, long startTimeMs) {
Paul Hud44e1b72023-06-16 02:07:42 +00002065 mTransactionId = transactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002066 mClock = clock;
2067 mStartTimeMs = startTimeMs;
2068 }
2069
2070 public long calculateRequestDurationMs() {
2071 final long stopTimeMs = mClock.elapsedRealtime();
2072 return stopTimeMs - mStartTimeMs;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002073 }
2074 }
2075
2076 private static class LegacyClientRequest extends ClientRequest {
2077 private final int mRequestCode;
2078
Paul Hu777ed052023-06-19 13:35:15 +00002079 private LegacyClientRequest(int transactionId, int requestCode, @NonNull Clock clock,
2080 long startTimeMs) {
2081 super(transactionId, clock, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002082 mRequestCode = requestCode;
2083 }
2084 }
2085
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002086 private abstract static class JavaBackendClientRequest extends ClientRequest {
2087 @Nullable
2088 private final Network mRequestedNetwork;
2089
Paul Hu777ed052023-06-19 13:35:15 +00002090 private JavaBackendClientRequest(int transactionId, @Nullable Network requestedNetwork,
2091 @NonNull Clock clock, long startTimeMs) {
2092 super(transactionId, clock, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002093 mRequestedNetwork = requestedNetwork;
2094 }
2095
2096 @Nullable
2097 public Network getRequestedNetwork() {
2098 return mRequestedNetwork;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002099 }
2100 }
2101
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002102 private static class AdvertiserClientRequest extends JavaBackendClientRequest {
Paul Hu777ed052023-06-19 13:35:15 +00002103 private AdvertiserClientRequest(int transactionId, @Nullable Network requestedNetwork,
2104 @NonNull Clock clock, long startTimeMs) {
2105 super(transactionId, requestedNetwork, clock, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002106 }
2107 }
2108
2109 private static class DiscoveryManagerRequest extends JavaBackendClientRequest {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002110 @NonNull
2111 private final MdnsListener mListener;
2112
Paul Hud44e1b72023-06-16 02:07:42 +00002113 private DiscoveryManagerRequest(int transactionId, @NonNull MdnsListener listener,
Paul Hu777ed052023-06-19 13:35:15 +00002114 @Nullable Network requestedNetwork, @NonNull Clock clock, long startTimeMs) {
2115 super(transactionId, requestedNetwork, clock, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002116 mListener = listener;
2117 }
2118 }
2119
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002120 /* Information tracked per client */
2121 private class ClientInfo {
2122
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002123 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002124 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002125 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002126 private NsdServiceInfo mResolvedService;
2127
Paul Hud44e1b72023-06-16 02:07:42 +00002128 /* A map from client request ID (listenerKey) to the request */
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002129 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08002130
Luke Huangf7277ed2021-07-12 21:15:10 +08002131 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002132 private boolean mIsPreSClient = false;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002133 private final int mUid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002134 // The flag of using java backend if the client's target SDK >= U
2135 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002136 // Store client logs
2137 private final SharedLog mClientLogs;
Paul Hucdef3532023-06-18 14:47:35 +00002138 // Report the nsd metrics data
2139 private final NetworkNsdReportedMetrics mMetrics;
Luke Huangf7277ed2021-07-12 21:15:10 +08002140
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002141 private ClientInfo(INsdManagerCallback cb, int uid, boolean useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +00002142 SharedLog sharedLog, NetworkNsdReportedMetrics metrics) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002143 mCb = cb;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002144 mUid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002145 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002146 mClientLogs = sharedLog;
2147 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Paul Hucdef3532023-06-18 14:47:35 +00002148 mMetrics = metrics;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002149 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002150
2151 @Override
2152 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06002153 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07002154 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002155 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002156 sb.append("mUseJavaBackend ").append(mUseJavaBackend).append("\n");
2157 sb.append("mUid ").append(mUid).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002158 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002159 int clientRequestId = mClientRequests.keyAt(i);
2160 sb.append("clientRequestId ")
2161 .append(clientRequestId)
2162 .append(" transactionId ").append(mClientRequests.valueAt(i).mTransactionId)
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002163 .append(" type ").append(
2164 mClientRequests.valueAt(i).getClass().getSimpleName())
2165 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07002166 }
2167 return sb.toString();
2168 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002169
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002170 private boolean isPreSClient() {
2171 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08002172 }
2173
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002174 private void setPreSClient() {
2175 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08002176 }
2177
Paul Hue4f5f252023-02-16 21:13:47 +08002178 private void unregisterMdnsListenerFromRequest(ClientRequest request) {
2179 final MdnsListener listener =
2180 ((DiscoveryManagerRequest) request).mListener;
2181 mMdnsDiscoveryManager.unregisterListener(
2182 listener.getListenedServiceType(), listener);
2183 }
2184
Dave Plattfeff2af2014-03-07 14:48:22 -08002185 // Remove any pending requests from the global map when we get rid of a client,
2186 // and send cancellations to the daemon.
2187 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00002188 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09002189 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002190 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002191 final int clientRequestId = mClientRequests.keyAt(i);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002192 final ClientRequest request = mClientRequests.valueAt(i);
Paul Hud44e1b72023-06-16 02:07:42 +00002193 final int transactionId = request.mTransactionId;
2194 mTransactionIdToClientInfoMap.remove(transactionId);
paulhub2225702021-11-17 09:35:33 +08002195 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002196 Log.d(TAG, "Terminating clientRequestId " + clientRequestId
2197 + " transactionId " + transactionId
2198 + " type " + mClientRequests.get(clientRequestId));
paulhub2225702021-11-17 09:35:33 +08002199 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002200
2201 if (request instanceof DiscoveryManagerRequest) {
Paul Hue4f5f252023-02-16 21:13:47 +08002202 unregisterMdnsListenerFromRequest(request);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002203 continue;
2204 }
2205
2206 if (request instanceof AdvertiserClientRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00002207 mAdvertiser.removeService(transactionId);
Paul Hu777ed052023-06-19 13:35:15 +00002208 mMetrics.reportServiceUnregistration(
2209 transactionId, request.calculateRequestDurationMs());
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002210 continue;
2211 }
2212
2213 if (!(request instanceof LegacyClientRequest)) {
2214 throw new IllegalStateException("Unknown request type: " + request.getClass());
2215 }
2216
2217 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08002218 case NsdManager.DISCOVER_SERVICES:
Paul Hud44e1b72023-06-16 02:07:42 +00002219 stopServiceDiscovery(transactionId);
Dave Plattfeff2af2014-03-07 14:48:22 -08002220 break;
2221 case NsdManager.RESOLVE_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002222 stopResolveService(transactionId);
Dave Plattfeff2af2014-03-07 14:48:22 -08002223 break;
2224 case NsdManager.REGISTER_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002225 unregisterService(transactionId);
Paul Hu777ed052023-06-19 13:35:15 +00002226 mMetrics.reportServiceUnregistration(
2227 transactionId, request.calculateRequestDurationMs());
Dave Plattfeff2af2014-03-07 14:48:22 -08002228 break;
2229 default:
2230 break;
2231 }
2232 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002233 mClientRequests.clear();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002234 updateMulticastLock();
2235 }
2236
2237 /**
2238 * Returns true if this client has any Java backend request that requests one of the given
2239 * networks.
2240 */
2241 boolean hasAnyJavaBackendRequestForNetworks(@NonNull ArraySet<Network> networks) {
2242 for (int i = 0; i < mClientRequests.size(); i++) {
2243 final ClientRequest req = mClientRequests.valueAt(i);
2244 if (!(req instanceof JavaBackendClientRequest)) {
2245 continue;
2246 }
2247 final Network reqNetwork = ((JavaBackendClientRequest) mClientRequests.valueAt(i))
2248 .getRequestedNetwork();
2249 if (MdnsUtils.isAnyNetworkMatched(reqNetwork, networks)) {
2250 return true;
2251 }
2252 }
2253 return false;
Dave Plattfeff2af2014-03-07 14:48:22 -08002254 }
2255
Paul Hud44e1b72023-06-16 02:07:42 +00002256 // mClientRequests is a sparse array of client request id -> ClientRequest. For a given
2257 // transaction id, return the corresponding client request id.
2258 private int getClientRequestId(final int transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002259 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002260 if (mClientRequests.valueAt(i).mTransactionId == transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002261 return mClientRequests.keyAt(i);
2262 }
Christopher Lane74411222014-04-25 18:39:07 -07002263 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002264 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07002265 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002266
Paul Hub2e67d32023-04-18 05:50:14 +00002267 private void log(String message) {
2268 mClientLogs.log(message);
2269 }
2270
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002271 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info) {
2272 try {
2273 mCb.onDiscoverServicesStarted(listenerKey, info);
2274 } catch (RemoteException e) {
2275 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
2276 }
2277 }
2278
2279 void onDiscoverServicesFailed(int listenerKey, int error) {
2280 try {
2281 mCb.onDiscoverServicesFailed(listenerKey, error);
2282 } catch (RemoteException e) {
2283 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
2284 }
2285 }
2286
2287 void onServiceFound(int listenerKey, NsdServiceInfo info) {
2288 try {
2289 mCb.onServiceFound(listenerKey, info);
2290 } catch (RemoteException e) {
2291 Log.e(TAG, "Error calling onServiceFound(", e);
2292 }
2293 }
2294
2295 void onServiceLost(int listenerKey, NsdServiceInfo info) {
2296 try {
2297 mCb.onServiceLost(listenerKey, info);
2298 } catch (RemoteException e) {
2299 Log.e(TAG, "Error calling onServiceLost(", e);
2300 }
2301 }
2302
2303 void onStopDiscoveryFailed(int listenerKey, int error) {
2304 try {
2305 mCb.onStopDiscoveryFailed(listenerKey, error);
2306 } catch (RemoteException e) {
2307 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
2308 }
2309 }
2310
2311 void onStopDiscoverySucceeded(int listenerKey) {
2312 try {
2313 mCb.onStopDiscoverySucceeded(listenerKey);
2314 } catch (RemoteException e) {
2315 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2316 }
2317 }
2318
Paul Hu777ed052023-06-19 13:35:15 +00002319 void onRegisterServiceFailedImmediately(int listenerKey, int error) {
2320 onRegisterServiceFailed(listenerKey, error, NO_TRANSACTION, 0 /* durationMs */);
2321 }
2322
2323 void onRegisterServiceFailed(int listenerKey, int error, int transactionId,
2324 long durationMs) {
2325 mMetrics.reportServiceRegistrationFailed(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002326 try {
2327 mCb.onRegisterServiceFailed(listenerKey, error);
2328 } catch (RemoteException e) {
2329 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2330 }
2331 }
2332
Paul Hu777ed052023-06-19 13:35:15 +00002333 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info, int transactionId,
2334 long durationMs) {
2335 mMetrics.reportServiceRegistrationSucceeded(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002336 try {
2337 mCb.onRegisterServiceSucceeded(listenerKey, info);
2338 } catch (RemoteException e) {
2339 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2340 }
2341 }
2342
2343 void onUnregisterServiceFailed(int listenerKey, int error) {
2344 try {
2345 mCb.onUnregisterServiceFailed(listenerKey, error);
2346 } catch (RemoteException e) {
2347 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2348 }
2349 }
2350
Paul Hu777ed052023-06-19 13:35:15 +00002351 void onUnregisterServiceSucceeded(int listenerKey, int transactionId, long durationMs) {
2352 mMetrics.reportServiceUnregistration(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002353 try {
2354 mCb.onUnregisterServiceSucceeded(listenerKey);
2355 } catch (RemoteException e) {
2356 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2357 }
2358 }
2359
2360 void onResolveServiceFailed(int listenerKey, int error) {
2361 try {
2362 mCb.onResolveServiceFailed(listenerKey, error);
2363 } catch (RemoteException e) {
2364 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2365 }
2366 }
2367
2368 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info) {
2369 try {
2370 mCb.onResolveServiceSucceeded(listenerKey, info);
2371 } catch (RemoteException e) {
2372 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2373 }
2374 }
Paul Hub58deb72022-12-26 09:24:42 +00002375
2376 void onStopResolutionFailed(int listenerKey, int error) {
2377 try {
2378 mCb.onStopResolutionFailed(listenerKey, error);
2379 } catch (RemoteException e) {
2380 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2381 }
2382 }
2383
2384 void onStopResolutionSucceeded(int listenerKey) {
2385 try {
2386 mCb.onStopResolutionSucceeded(listenerKey);
2387 } catch (RemoteException e) {
2388 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2389 }
2390 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002391
2392 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
2393 try {
2394 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2395 } catch (RemoteException e) {
2396 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2397 }
2398 }
2399
2400 void onServiceUpdated(int listenerKey, NsdServiceInfo info) {
2401 try {
2402 mCb.onServiceUpdated(listenerKey, info);
2403 } catch (RemoteException e) {
2404 Log.e(TAG, "Error calling onServiceUpdated", e);
2405 }
2406 }
2407
2408 void onServiceUpdatedLost(int listenerKey) {
2409 try {
2410 mCb.onServiceUpdatedLost(listenerKey);
2411 } catch (RemoteException e) {
2412 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2413 }
2414 }
2415
2416 void onServiceInfoCallbackUnregistered(int listenerKey) {
2417 try {
2418 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2419 } catch (RemoteException e) {
2420 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2421 }
2422 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002423 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002424}