blob: b06e9cb67b07f85bad32974734101c98f1f6c406 [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;
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090029
Paul Hu23fa2022023-01-13 22:57:24 +080030import android.annotation.NonNull;
Paul Hu4bd98ef2023-01-12 13:42:07 +080031import android.annotation.Nullable;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090032import android.app.ActivityManager;
paulhua262cc12019-08-12 16:25:11 +080033import android.content.Context;
Irfan Sheriff75006652012-04-17 23:15:29 -070034import android.content.Intent;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090035import android.net.ConnectivityManager;
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +090036import android.net.INetd;
Paul Hu75069ed2023-01-14 00:31:09 +080037import android.net.InetAddresses;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090038import android.net.LinkProperties;
39import android.net.Network;
paulhu2b9ed952022-02-10 21:58:32 +080040import android.net.mdns.aidl.DiscoveryInfo;
41import android.net.mdns.aidl.GetAddressInfo;
42import android.net.mdns.aidl.IMDnsEventListener;
43import android.net.mdns.aidl.RegistrationInfo;
44import android.net.mdns.aidl.ResolutionInfo;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070045import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090046import android.net.nsd.INsdManagerCallback;
47import android.net.nsd.INsdServiceConnector;
paulhu2b9ed952022-02-10 21:58:32 +080048import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070049import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080050import android.net.nsd.NsdServiceInfo;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090051import android.net.wifi.WifiManager;
Paul Hub2e67d32023-04-18 05:50:14 +000052import android.os.Binder;
Hugo Benichi803a2f02017-04-24 11:35:06 +090053import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080054import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090055import android.os.IBinder;
Paul Hu4bd98ef2023-01-12 13:42:07 +080056import android.os.Looper;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070057import android.os.Message;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090058import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070059import android.os.UserHandle;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090060import android.provider.DeviceConfig;
Paul Hu23fa2022023-01-13 22:57:24 +080061import android.text.TextUtils;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090062import android.util.ArraySet;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090063import android.util.Log;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +090064import android.util.Pair;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070065import android.util.SparseArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070066
paulhua262cc12019-08-12 16:25:11 +080067import com.android.internal.annotations.VisibleForTesting;
Paul Hub2e67d32023-04-18 05:50:14 +000068import com.android.internal.util.IndentingPrintWriter;
paulhua262cc12019-08-12 16:25:11 +080069import com.android.internal.util.State;
70import com.android.internal.util.StateMachine;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090071import com.android.net.module.util.CollectionUtils;
Paul Hu4bd98ef2023-01-12 13:42:07 +080072import com.android.net.module.util.DeviceConfigUtils;
Yuyang Huanga6a6ff92023-04-24 13:33:34 +090073import com.android.net.module.util.InetAddressUtils;
paulhu3ffffe72021-09-16 10:15:22 +080074import com.android.net.module.util.PermissionUtils;
Paul Hub2e67d32023-04-18 05:50:14 +000075import com.android.net.module.util.SharedLog;
Paul Hu4bd98ef2023-01-12 13:42:07 +080076import com.android.server.connectivity.mdns.ExecutorProvider;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090077import com.android.server.connectivity.mdns.MdnsAdvertiser;
Paul Hu4bd98ef2023-01-12 13:42:07 +080078import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090079import com.android.server.connectivity.mdns.MdnsInterfaceSocket;
Paul Hu4bd98ef2023-01-12 13:42:07 +080080import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
Paul Hu23fa2022023-01-13 22:57:24 +080081import com.android.server.connectivity.mdns.MdnsSearchOptions;
82import com.android.server.connectivity.mdns.MdnsServiceBrowserListener;
83import com.android.server.connectivity.mdns.MdnsServiceInfo;
Paul Hu4bd98ef2023-01-12 13:42:07 +080084import com.android.server.connectivity.mdns.MdnsSocketProvider;
Yuyang Huangde802c82023-05-02 17:14:22 +090085import com.android.server.connectivity.mdns.util.MdnsUtils;
paulhua262cc12019-08-12 16:25:11 +080086
Irfan Sheriff77ec5582012-03-22 17:01:39 -070087import java.io.FileDescriptor;
88import java.io.PrintWriter;
Yuyang Huangaa0e9602023-03-17 12:43:09 +090089import java.net.Inet6Address;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070090import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090091import java.net.NetworkInterface;
92import java.net.SocketException;
93import java.net.UnknownHostException;
Paul Hu2b865912023-03-06 14:27:53 +080094import java.util.ArrayList;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +090095import java.util.Arrays;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070096import java.util.HashMap;
Paul Hu23fa2022023-01-13 22:57:24 +080097import java.util.List;
Paul Hu75069ed2023-01-14 00:31:09 +080098import java.util.Map;
Paul Hu23fa2022023-01-13 22:57:24 +080099import java.util.regex.Matcher;
100import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700101
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700102/**
103 * Network Service Discovery Service handles remote service discovery operation requests by
104 * implementing the INsdManager interface.
105 *
106 * @hide
107 */
108public class NsdService extends INsdManager.Stub {
109 private static final String TAG = "NsdService";
110 private static final String MDNS_TAG = "mDnsConnector";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900111 /**
112 * Enable discovery using the Java DiscoveryManager, instead of the legacy mdnsresponder
113 * implementation.
114 */
Paul Hu4bd98ef2023-01-12 13:42:07 +0800115 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +0800116 private static final String LOCAL_DOMAIN_NAME = "local";
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700117
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900118 /**
119 * Enable advertising using the Java MdnsAdvertiser, instead of the legacy mdnsresponder
120 * implementation.
121 */
122 private static final String MDNS_ADVERTISER_VERSION = "mdns_advertiser_version";
123
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900124 /**
125 * Comma-separated list of type:flag mappings indicating the flags to use to allowlist
126 * discovery/advertising using MdnsDiscoveryManager / MdnsAdvertiser for a given type.
127 *
128 * For example _mytype._tcp.local and _othertype._tcp.local would be configured with:
129 * _mytype._tcp:mytype,_othertype._tcp.local:othertype
130 *
131 * In which case the flags:
132 * "mdns_discovery_manager_allowlist_mytype_version",
133 * "mdns_advertiser_allowlist_mytype_version",
134 * "mdns_discovery_manager_allowlist_othertype_version",
135 * "mdns_advertiser_allowlist_othertype_version"
136 * would be used to toggle MdnsDiscoveryManager / MdnsAdvertiser for each type. The flags will
137 * be read with
138 * {@link DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)}.
139 *
140 * @see #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX
141 * @see #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX
142 * @see #MDNS_ALLOWLIST_FLAG_SUFFIX
143 */
144 private static final String MDNS_TYPE_ALLOWLIST_FLAGS = "mdns_type_allowlist_flags";
145
146 private static final String MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX =
147 "mdns_discovery_manager_allowlist_";
148 private static final String MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX =
149 "mdns_advertiser_allowlist_";
150 private static final String MDNS_ALLOWLIST_FLAG_SUFFIX = "_version";
151
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900152 @VisibleForTesting
153 static final String MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
154 "mdns_config_running_app_active_importance_cutoff";
155 @VisibleForTesting
156 static final int DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
157 ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
158 private final int mRunningAppActiveImportanceCutoff;
159
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900160 public static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +0000161 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900162 private static final int IFACE_IDX_ANY = 0;
Paul Hu14667de2023-04-17 22:42:47 +0800163 private static final SharedLog LOGGER = new SharedLog("serviceDiscovery");
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700164
Hugo Benichi32be63d2017-04-05 14:06:11 +0900165 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900166 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +0800167 private final MDnsManager mMDnsManager;
168 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900169 @NonNull
170 private final Dependencies mDeps;
171 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800172 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900173 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800174 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900175 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800176 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900177 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900178 private final MdnsAdvertiser mAdvertiser;
Paul Hu14667de2023-04-17 22:42:47 +0800179 private final SharedLog mServiceLogs = LOGGER.forSubComponent(TAG);
Paul Hu23fa2022023-01-13 22:57:24 +0800180 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800181 // state machine thread. If change this outside state machine, it will need to introduce
182 // synchronization.
183 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800184 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700185
186 /**
187 * Clients receiving asynchronous messages
188 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900189 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700190
Paul Hud44e1b72023-06-16 02:07:42 +0000191 /* A map from transaction(unique) id to client info */
192 private final SparseArray<ClientInfo> mTransactionIdToClientInfoMap = new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700193
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900194 // Note this is not final to avoid depending on the Wi-Fi service starting before NsdService
195 @Nullable
196 private WifiManager.MulticastLock mHeldMulticastLock;
197 // Fulfilled network requests that require the Wi-Fi lock: key is the obtained Network
198 // (non-null), value is the requested Network (nullable)
199 @NonNull
200 private final ArraySet<Network> mWifiLockRequiredNetworks = new ArraySet<>();
201 @NonNull
202 private final ArraySet<Integer> mRunningAppActiveUids = new ArraySet<>();
203
Luke Huang05298582021-06-13 16:52:05 +0000204 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700205
Hugo Benichi32be63d2017-04-05 14:06:11 +0900206 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700207 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800208 // The count of the connected legacy clients.
209 private int mLegacyClientCount = 0;
Paul Hub2e67d32023-04-18 05:50:14 +0000210 // The number of client that ever connected.
211 private int mClientNumberId = 1;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700212
Paul Hu23fa2022023-01-13 22:57:24 +0800213 private static class MdnsListener implements MdnsServiceBrowserListener {
Paul Hud44e1b72023-06-16 02:07:42 +0000214 protected final int mClientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800215 protected final int mTransactionId;
216 @NonNull
217 protected final NsdServiceInfo mReqServiceInfo;
218 @NonNull
219 protected final String mListenedServiceType;
220
Paul Hud44e1b72023-06-16 02:07:42 +0000221 MdnsListener(int clientRequestId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
Paul Hu23fa2022023-01-13 22:57:24 +0800222 @NonNull String listenedServiceType) {
Paul Hud44e1b72023-06-16 02:07:42 +0000223 mClientRequestId = clientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800224 mTransactionId = transactionId;
225 mReqServiceInfo = reqServiceInfo;
226 mListenedServiceType = listenedServiceType;
227 }
228
229 @NonNull
230 public String getListenedServiceType() {
231 return mListenedServiceType;
232 }
233
234 @Override
235 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) { }
236
237 @Override
238 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
239
240 @Override
241 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
242
243 @Override
244 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) { }
245
246 @Override
247 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
248
249 @Override
250 public void onSearchStoppedWithError(int error) { }
251
252 @Override
253 public void onSearchFailedToStart() { }
254
255 @Override
256 public void onDiscoveryQuerySent(@NonNull List<String> subtypes, int transactionId) { }
257
258 @Override
259 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
260 }
261
262 private class DiscoveryListener extends MdnsListener {
263
Paul Hud44e1b72023-06-16 02:07:42 +0000264 DiscoveryListener(int clientRequestId, int transactionId,
265 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
266 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800267 }
268
269 @Override
270 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu019621e2023-01-13 23:26:49 +0800271 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
272 NsdManager.SERVICE_FOUND,
Paul Hud44e1b72023-06-16 02:07:42 +0000273 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800274 }
275
276 @Override
277 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800278 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
279 NsdManager.SERVICE_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000280 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800281 }
282 }
283
Paul Hu75069ed2023-01-14 00:31:09 +0800284 private class ResolutionListener extends MdnsListener {
285
Paul Hud44e1b72023-06-16 02:07:42 +0000286 ResolutionListener(int clientRequestId, int transactionId,
287 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
288 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800289 }
290
291 @Override
292 public void onServiceFound(MdnsServiceInfo serviceInfo) {
293 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
294 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
Paul Hud44e1b72023-06-16 02:07:42 +0000295 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu75069ed2023-01-14 00:31:09 +0800296 }
297 }
298
Paul Hu30bd70d2023-02-07 13:20:56 +0000299 private class ServiceInfoListener extends MdnsListener {
300
Paul Hud44e1b72023-06-16 02:07:42 +0000301 ServiceInfoListener(int clientRequestId, int transactionId,
302 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
303 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +0000304 }
305
306 @Override
307 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) {
308 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
309 NsdManager.SERVICE_UPDATED,
Paul Hud44e1b72023-06-16 02:07:42 +0000310 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000311 }
312
313 @Override
314 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) {
315 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
316 NsdManager.SERVICE_UPDATED,
Paul Hud44e1b72023-06-16 02:07:42 +0000317 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000318 }
319
320 @Override
321 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) {
322 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
323 NsdManager.SERVICE_UPDATED_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000324 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000325 }
326 }
327
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900328 private class SocketRequestMonitor implements MdnsSocketProvider.SocketRequestMonitor {
329 @Override
330 public void onSocketRequestFulfilled(@Nullable Network socketNetwork,
331 @NonNull MdnsInterfaceSocket socket, @NonNull int[] transports) {
332 // The network may be null for Wi-Fi SoftAp interfaces (tethering), but there is no APF
333 // filtering on such interfaces, so taking the multicast lock is not necessary to
334 // disable APF filtering of multicast.
335 if (socketNetwork == null
336 || !CollectionUtils.contains(transports, TRANSPORT_WIFI)
337 || CollectionUtils.contains(transports, TRANSPORT_VPN)) {
338 return;
339 }
340
341 if (mWifiLockRequiredNetworks.add(socketNetwork)) {
342 updateMulticastLock();
343 }
344 }
345
346 @Override
347 public void onSocketDestroyed(@Nullable Network socketNetwork,
348 @NonNull MdnsInterfaceSocket socket) {
349 if (mWifiLockRequiredNetworks.remove(socketNetwork)) {
350 updateMulticastLock();
351 }
352 }
353 }
354
355 private class UidImportanceListener implements ActivityManager.OnUidImportanceListener {
356 private final Handler mHandler;
357
358 private UidImportanceListener(Handler handler) {
359 mHandler = handler;
360 }
361
362 @Override
363 public void onUidImportance(int uid, int importance) {
364 mHandler.post(() -> handleUidImportanceChanged(uid, importance));
365 }
366 }
367
368 private void handleUidImportanceChanged(int uid, int importance) {
369 // Lower importance values are more "important"
370 final boolean modified = importance <= mRunningAppActiveImportanceCutoff
371 ? mRunningAppActiveUids.add(uid)
372 : mRunningAppActiveUids.remove(uid);
373 if (modified) {
374 updateMulticastLock();
375 }
376 }
377
378 /**
379 * Take or release the lock based on updated internal state.
380 *
381 * This determines whether the lock needs to be held based on
382 * {@link #mWifiLockRequiredNetworks}, {@link #mRunningAppActiveUids} and
383 * {@link ClientInfo#mClientRequests}, so it must be called after any of the these have been
384 * updated.
385 */
386 private void updateMulticastLock() {
387 final int needsLockUid = getMulticastLockNeededUid();
388 if (needsLockUid >= 0 && mHeldMulticastLock == null) {
389 final WifiManager wm = mContext.getSystemService(WifiManager.class);
390 if (wm == null) {
391 Log.wtf(TAG, "Got a TRANSPORT_WIFI network without WifiManager");
392 return;
393 }
394 mHeldMulticastLock = wm.createMulticastLock(TAG);
395 mHeldMulticastLock.acquire();
396 mServiceLogs.log("Taking multicast lock for uid " + needsLockUid);
397 } else if (needsLockUid < 0 && mHeldMulticastLock != null) {
398 mHeldMulticastLock.release();
399 mHeldMulticastLock = null;
400 mServiceLogs.log("Released multicast lock");
401 }
402 }
403
404 /**
405 * @return The UID of an app requiring the multicast lock, or -1 if none.
406 */
407 private int getMulticastLockNeededUid() {
408 if (mWifiLockRequiredNetworks.size() == 0) {
409 // Return early if NSD is not active, or not on any relevant network
410 return -1;
411 }
Paul Hud44e1b72023-06-16 02:07:42 +0000412 for (int i = 0; i < mTransactionIdToClientInfoMap.size(); i++) {
413 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.valueAt(i);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900414 if (!mRunningAppActiveUids.contains(clientInfo.mUid)) {
415 // Ignore non-active UIDs
416 continue;
417 }
418
419 if (clientInfo.hasAnyJavaBackendRequestForNetworks(mWifiLockRequiredNetworks)) {
420 return clientInfo.mUid;
421 }
422 }
423 return -1;
424 }
425
Paul Hu019621e2023-01-13 23:26:49 +0800426 /**
427 * Data class of mdns service callback information.
428 */
429 private static class MdnsEvent {
Paul Hud44e1b72023-06-16 02:07:42 +0000430 final int mClientRequestId;
Paul Hu019621e2023-01-13 23:26:49 +0800431 @NonNull
Paul Hu019621e2023-01-13 23:26:49 +0800432 final MdnsServiceInfo mMdnsServiceInfo;
433
Paul Hud44e1b72023-06-16 02:07:42 +0000434 MdnsEvent(int clientRequestId, @NonNull MdnsServiceInfo mdnsServiceInfo) {
435 mClientRequestId = clientRequestId;
Paul Hu019621e2023-01-13 23:26:49 +0800436 mMdnsServiceInfo = mdnsServiceInfo;
437 }
438 }
439
Irfan Sheriff75006652012-04-17 23:15:29 -0700440 private class NsdStateMachine extends StateMachine {
441
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700442 private final DefaultState mDefaultState = new DefaultState();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700443 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700444
445 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700446 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900447 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700448 }
449
Luke Huang92860f92021-06-23 06:29:30 +0000450 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800451 if (mIsDaemonStarted) {
452 if (DBG) Log.d(TAG, "Daemon is already started.");
453 return;
454 }
455 mMDnsManager.registerEventListener(mMDnsEventCallback);
456 mMDnsManager.startDaemon();
457 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000458 maybeScheduleStop();
Paul Hub2e67d32023-04-18 05:50:14 +0000459 mServiceLogs.log("Start mdns_responder daemon");
Luke Huang05298582021-06-13 16:52:05 +0000460 }
461
paulhu2b9ed952022-02-10 21:58:32 +0800462 private void maybeStopDaemon() {
463 if (!mIsDaemonStarted) {
464 if (DBG) Log.d(TAG, "Daemon has not been started.");
465 return;
466 }
467 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
468 mMDnsManager.stopDaemon();
469 mIsDaemonStarted = false;
Paul Hub2e67d32023-04-18 05:50:14 +0000470 mServiceLogs.log("Stop mdns_responder daemon");
paulhu2b9ed952022-02-10 21:58:32 +0800471 }
472
Luke Huang92860f92021-06-23 06:29:30 +0000473 private boolean isAnyRequestActive() {
Paul Hud44e1b72023-06-16 02:07:42 +0000474 return mTransactionIdToClientInfoMap.size() != 0;
Luke Huang92860f92021-06-23 06:29:30 +0000475 }
476
477 private void scheduleStop() {
478 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
479 }
480 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800481 // The native daemon should stay alive and can't be cleanup
482 // if any legacy client connected.
483 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000484 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000485 }
486 }
487
Luke Huang92860f92021-06-23 06:29:30 +0000488 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000489 this.removeMessages(NsdManager.DAEMON_CLEANUP);
490 }
491
Paul Hu23fa2022023-01-13 22:57:24 +0800492 private void maybeStartMonitoringSockets() {
493 if (mIsMonitoringSocketsStarted) {
494 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
495 return;
496 }
497
498 mMdnsSocketProvider.startMonitoringSockets();
499 mIsMonitoringSocketsStarted = true;
500 }
501
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900502 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
503 if (!mIsMonitoringSocketsStarted) return;
504 if (isAnyRequestActive()) return;
505
Paul Hu58f20602023-02-18 11:41:07 +0800506 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800507 mIsMonitoringSocketsStarted = false;
508 }
509
Hugo Benichi803a2f02017-04-24 11:35:06 +0900510 NsdStateMachine(String name, Handler handler) {
511 super(name, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700512 addState(mDefaultState);
Irfan Sheriff75006652012-04-17 23:15:29 -0700513 addState(mEnabledState, mDefaultState);
paulhu5568f452021-11-30 13:31:29 +0800514 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900515 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700516 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700517 }
518
519 class DefaultState extends State {
520 @Override
521 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900522 final ClientInfo cInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000523 final int clientRequestId = msg.arg2;
Irfan Sheriff75006652012-04-17 23:15:29 -0700524 switch (msg.what) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900525 case NsdManager.REGISTER_CLIENT:
Paul Hu2e0a88c2023-03-09 16:05:01 +0800526 final ConnectorArgs arg = (ConnectorArgs) msg.obj;
527 final INsdManagerCallback cb = arg.callback;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900528 try {
Paul Hu2e0a88c2023-03-09 16:05:01 +0800529 cb.asBinder().linkToDeath(arg.connector, 0);
Paul Hub2e67d32023-04-18 05:50:14 +0000530 final String tag = "Client" + arg.uid + "-" + mClientNumberId++;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900531 cInfo = new ClientInfo(cb, arg.uid, arg.useJavaBackend,
Paul Hub2e67d32023-04-18 05:50:14 +0000532 mServiceLogs.forSubComponent(tag));
Paul Hu2e0a88c2023-03-09 16:05:01 +0800533 mClients.put(arg.connector, cInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900534 } catch (RemoteException e) {
Paul Hud44e1b72023-06-16 02:07:42 +0000535 Log.w(TAG, "Client request id " + clientRequestId
536 + " has already died");
Irfan Sheriff75006652012-04-17 23:15:29 -0700537 }
538 break;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900539 case NsdManager.UNREGISTER_CLIENT:
540 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
541 cInfo = mClients.remove(connector);
Dave Plattfeff2af2014-03-07 14:48:22 -0800542 if (cInfo != null) {
543 cInfo.expungeAllRequests();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900544 if (cInfo.isPreSClient()) {
Luke Huangf7277ed2021-07-12 21:15:10 +0800545 mLegacyClientCount -= 1;
546 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800547 }
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900548 maybeStopMonitoringSocketsIfNoActiveRequest();
Luke Huangf7277ed2021-07-12 21:15:10 +0800549 maybeScheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700550 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700551 case NsdManager.DISCOVER_SERVICES:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900552 cInfo = getClientInfoForReply(msg);
553 if (cInfo != null) {
554 cInfo.onDiscoverServicesFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000555 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900556 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700557 break;
558 case NsdManager.STOP_DISCOVERY:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900559 cInfo = getClientInfoForReply(msg);
560 if (cInfo != null) {
561 cInfo.onStopDiscoveryFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000562 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900563 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700564 break;
565 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900566 cInfo = getClientInfoForReply(msg);
567 if (cInfo != null) {
568 cInfo.onRegisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000569 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900570 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700571 break;
572 case NsdManager.UNREGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900573 cInfo = getClientInfoForReply(msg);
574 if (cInfo != null) {
575 cInfo.onUnregisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000576 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900577 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700578 break;
579 case NsdManager.RESOLVE_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900580 cInfo = getClientInfoForReply(msg);
581 if (cInfo != null) {
582 cInfo.onResolveServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000583 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900584 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700585 break;
Paul Hub58deb72022-12-26 09:24:42 +0000586 case NsdManager.STOP_RESOLUTION:
587 cInfo = getClientInfoForReply(msg);
588 if (cInfo != null) {
589 cInfo.onStopResolutionFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000590 clientRequestId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hub58deb72022-12-26 09:24:42 +0000591 }
592 break;
Paul Hu18aeccc2022-12-27 08:48:48 +0000593 case NsdManager.REGISTER_SERVICE_CALLBACK:
594 cInfo = getClientInfoForReply(msg);
595 if (cInfo != null) {
596 cInfo.onServiceInfoCallbackRegistrationFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000597 clientRequestId, NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +0000598 }
599 break;
Luke Huang05298582021-06-13 16:52:05 +0000600 case NsdManager.DAEMON_CLEANUP:
paulhu2b9ed952022-02-10 21:58:32 +0800601 maybeStopDaemon();
Luke Huang05298582021-06-13 16:52:05 +0000602 break;
Luke Huangf7277ed2021-07-12 21:15:10 +0800603 // This event should be only sent by the legacy (target SDK < S) clients.
604 // Mark the sending client as legacy.
605 case NsdManager.DAEMON_STARTUP:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900606 cInfo = getClientInfoForReply(msg);
Luke Huangf7277ed2021-07-12 21:15:10 +0800607 if (cInfo != null) {
608 cancelStop();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900609 cInfo.setPreSClient();
Luke Huangf7277ed2021-07-12 21:15:10 +0800610 mLegacyClientCount += 1;
611 maybeStartDaemon();
612 }
613 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700614 default:
paulhub2225702021-11-17 09:35:33 +0800615 Log.e(TAG, "Unhandled " + msg);
Irfan Sheriff75006652012-04-17 23:15:29 -0700616 return NOT_HANDLED;
617 }
618 return HANDLED;
619 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900620
621 private ClientInfo getClientInfoForReply(Message msg) {
622 final ListenerArgs args = (ListenerArgs) msg.obj;
623 return mClients.get(args.connector);
624 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700625 }
626
Irfan Sheriff75006652012-04-17 23:15:29 -0700627 class EnabledState extends State {
628 @Override
629 public void enter() {
630 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700631 }
632
633 @Override
634 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000635 // TODO: it is incorrect to stop the daemon without expunging all requests
636 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000637 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700638 }
639
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700640 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900641 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800642 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700643 return true;
644 }
645 return false;
646 }
647
Paul Hud44e1b72023-06-16 02:07:42 +0000648 private void storeLegacyRequestMap(int clientRequestId, int transactionId,
649 ClientInfo clientInfo, int what) {
650 clientInfo.mClientRequests.put(
651 clientRequestId, new LegacyClientRequest(transactionId, what));
652 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000653 // Remove the cleanup event because here comes a new request.
654 cancelStop();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700655 }
656
Paul Hud44e1b72023-06-16 02:07:42 +0000657 private void storeAdvertiserRequestMap(int clientRequestId, int transactionId,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900658 ClientInfo clientInfo, @Nullable Network requestedNetwork) {
Paul Hud44e1b72023-06-16 02:07:42 +0000659 clientInfo.mClientRequests.put(clientRequestId,
660 new AdvertiserClientRequest(transactionId, requestedNetwork));
661 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900662 updateMulticastLock();
Paul Hu23fa2022023-01-13 22:57:24 +0800663 }
664
Paul Hud44e1b72023-06-16 02:07:42 +0000665 private void removeRequestMap(
666 int clientRequestId, int transactionId, ClientInfo clientInfo) {
667 final ClientRequest existing = clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900668 if (existing == null) return;
Paul Hud44e1b72023-06-16 02:07:42 +0000669 clientInfo.mClientRequests.remove(clientRequestId);
670 mTransactionIdToClientInfoMap.remove(transactionId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900671
672 if (existing instanceof LegacyClientRequest) {
673 maybeScheduleStop();
674 } else {
675 maybeStopMonitoringSocketsIfNoActiveRequest();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900676 updateMulticastLock();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900677 }
678 }
679
Paul Hud44e1b72023-06-16 02:07:42 +0000680 private void storeDiscoveryManagerRequestMap(int clientRequestId, int transactionId,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900681 MdnsListener listener, ClientInfo clientInfo,
682 @Nullable Network requestedNetwork) {
Paul Hud44e1b72023-06-16 02:07:42 +0000683 clientInfo.mClientRequests.put(clientRequestId,
684 new DiscoveryManagerRequest(transactionId, listener, requestedNetwork));
685 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900686 updateMulticastLock();
Paul Hu23fa2022023-01-13 22:57:24 +0800687 }
688
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900689 /**
690 * Truncate a service name to up to 63 UTF-8 bytes.
691 *
692 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
693 * names used in registerService follows historical behavior (see mdnsresponder
694 * handle_regservice_request).
695 */
696 @NonNull
697 private String truncateServiceName(@NonNull String originalName) {
Yuyang Huangde802c82023-05-02 17:14:22 +0900698 return MdnsUtils.truncateServiceName(originalName, MAX_LABEL_LENGTH);
Paul Hu23fa2022023-01-13 22:57:24 +0800699 }
700
Paul Hud44e1b72023-06-16 02:07:42 +0000701 private void stopDiscoveryManagerRequest(ClientRequest request, int clientRequestId,
702 int transactionId, ClientInfo clientInfo) {
Paul Hue4f5f252023-02-16 21:13:47 +0800703 clientInfo.unregisterMdnsListenerFromRequest(request);
Paul Hud44e1b72023-06-16 02:07:42 +0000704 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hue4f5f252023-02-16 21:13:47 +0800705 }
706
Irfan Sheriff75006652012-04-17 23:15:29 -0700707 @Override
708 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900709 final ClientInfo clientInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000710 final int transactionId;
711 final int clientRequestId = msg.arg2;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900712 final ListenerArgs args;
Irfan Sheriff75006652012-04-17 23:15:29 -0700713 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800714 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800715 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900716 args = (ListenerArgs) msg.obj;
717 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000718 // If the binder death notification for a INsdManagerCallback was received
719 // before any calls are received by NsdService, the clientInfo would be
720 // cleared and cause NPE. Add a null check here to prevent this corner case.
721 if (clientInfo == null) {
722 Log.e(TAG, "Unknown connector in discovery");
723 break;
724 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700725
726 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900727 clientInfo.onDiscoverServicesFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000728 clientRequestId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriff75006652012-04-17 23:15:29 -0700729 break;
730 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700731
Paul Hu23fa2022023-01-13 22:57:24 +0800732 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000733 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900734 final Pair<String, String> typeAndSubtype =
735 parseTypeAndSubtype(info.getServiceType());
736 final String serviceType = typeAndSubtype == null
737 ? null : typeAndSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800738 if (clientInfo.mUseJavaBackend
739 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900740 || useDiscoveryManagerForType(serviceType)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800741 if (serviceType == null) {
Paul Hud44e1b72023-06-16 02:07:42 +0000742 clientInfo.onDiscoverServicesFailed(clientRequestId,
Paul Hu23fa2022023-01-13 22:57:24 +0800743 NsdManager.FAILURE_INTERNAL_ERROR);
744 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700745 }
Paul Hu23fa2022023-01-13 22:57:24 +0800746
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900747 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800748 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +0000749 final MdnsListener listener = new DiscoveryListener(clientRequestId,
750 transactionId, info, listenServiceType);
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900751 final MdnsSearchOptions.Builder optionsBuilder =
752 MdnsSearchOptions.newBuilder()
753 .setNetwork(info.getNetwork())
Yuyang Huangff963222023-06-01 18:42:42 +0900754 .setRemoveExpiredService(true)
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900755 .setIsPassiveMode(true);
756 if (typeAndSubtype.second != null) {
757 // The parsing ensures subtype starts with an underscore.
758 // MdnsSearchOptions expects the underscore to not be present.
759 optionsBuilder.addSubtype(typeAndSubtype.second.substring(1));
760 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900761 mMdnsDiscoveryManager.registerListener(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900762 listenServiceType, listener, optionsBuilder.build());
Paul Hud44e1b72023-06-16 02:07:42 +0000763 storeDiscoveryManagerRequestMap(clientRequestId, transactionId,
764 listener, clientInfo, info.getNetwork());
765 clientInfo.onDiscoverServicesStarted(clientRequestId, info);
766 clientInfo.log("Register a DiscoveryListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +0000767 + " for service type:" + listenServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700768 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800769 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000770 if (discoverServices(transactionId, info)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800771 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +0000772 Log.d(TAG, "Discover " + msg.arg2 + " " + transactionId
Paul Hu23fa2022023-01-13 22:57:24 +0800773 + info.getServiceType());
774 }
Paul Hud44e1b72023-06-16 02:07:42 +0000775 storeLegacyRequestMap(
776 clientRequestId, transactionId, clientInfo, msg.what);
777 clientInfo.onDiscoverServicesStarted(clientRequestId, info);
Paul Hu23fa2022023-01-13 22:57:24 +0800778 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000779 stopServiceDiscovery(transactionId);
780 clientInfo.onDiscoverServicesFailed(clientRequestId,
Paul Hu23fa2022023-01-13 22:57:24 +0800781 NsdManager.FAILURE_INTERNAL_ERROR);
782 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700783 }
784 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800785 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900786 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800787 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900788 args = (ListenerArgs) msg.obj;
789 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000790 // If the binder death notification for a INsdManagerCallback was received
791 // before any calls are received by NsdService, the clientInfo would be
792 // cleared and cause NPE. Add a null check here to prevent this corner case.
793 if (clientInfo == null) {
794 Log.e(TAG, "Unknown connector in stop discovery");
795 break;
796 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700797
Paul Hud44e1b72023-06-16 02:07:42 +0000798 final ClientRequest request =
799 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900800 if (request == null) {
801 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700802 break;
803 }
Paul Hud44e1b72023-06-16 02:07:42 +0000804 transactionId = request.mTransactionId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900805 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
806 // point, so this needs to check the type of the original request to
807 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900808 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +0000809 stopDiscoveryManagerRequest(
810 request, clientRequestId, transactionId, clientInfo);
811 clientInfo.onStopDiscoverySucceeded(clientRequestId);
812 clientInfo.log("Unregister the DiscoveryListener " + transactionId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700813 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000814 removeRequestMap(clientRequestId, transactionId, clientInfo);
815 if (stopServiceDiscovery(transactionId)) {
816 clientInfo.onStopDiscoverySucceeded(clientRequestId);
Paul Hu23fa2022023-01-13 22:57:24 +0800817 } else {
818 clientInfo.onStopDiscoveryFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000819 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu23fa2022023-01-13 22:57:24 +0800820 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700821 }
822 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900823 }
824 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800825 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900826 args = (ListenerArgs) msg.obj;
827 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000828 // If the binder death notification for a INsdManagerCallback was received
829 // before any calls are received by NsdService, the clientInfo would be
830 // cleared and cause NPE. Add a null check here to prevent this corner case.
831 if (clientInfo == null) {
832 Log.e(TAG, "Unknown connector in registration");
833 break;
834 }
835
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700836 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900837 clientInfo.onRegisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000838 clientRequestId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700839 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700840 }
841
Paul Hud44e1b72023-06-16 02:07:42 +0000842 transactionId = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900843 final NsdServiceInfo serviceInfo = args.serviceInfo;
844 final String serviceType = serviceInfo.getServiceType();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900845 final Pair<String, String> typeSubtype = parseTypeAndSubtype(serviceType);
846 final String registerServiceType = typeSubtype == null
847 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800848 if (clientInfo.mUseJavaBackend
849 || mDeps.isMdnsAdvertiserEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900850 || useAdvertiserForType(registerServiceType)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900851 if (registerServiceType == null) {
852 Log.e(TAG, "Invalid service type: " + serviceType);
Paul Hud44e1b72023-06-16 02:07:42 +0000853 clientInfo.onRegisterServiceFailed(clientRequestId,
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900854 NsdManager.FAILURE_INTERNAL_ERROR);
855 break;
856 }
857 serviceInfo.setServiceType(registerServiceType);
858 serviceInfo.setServiceName(truncateServiceName(
859 serviceInfo.getServiceName()));
860
861 maybeStartMonitoringSockets();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900862 // TODO: pass in the subtype as well. Including the subtype in the
863 // service type would generate service instance names like
864 // Name._subtype._sub._type._tcp, which is incorrect
865 // (it should be Name._type._tcp).
Paul Hud44e1b72023-06-16 02:07:42 +0000866 mAdvertiser.addService(transactionId, serviceInfo, typeSubtype.second);
867 storeAdvertiserRequestMap(clientRequestId, transactionId, clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900868 serviceInfo.getNetwork());
Irfan Sheriff75006652012-04-17 23:15:29 -0700869 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900870 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000871 if (registerService(transactionId, serviceInfo)) {
872 if (DBG) {
873 Log.d(TAG, "Register " + clientRequestId
874 + " " + transactionId);
875 }
876 storeLegacyRequestMap(
877 clientRequestId, transactionId, clientInfo, msg.what);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900878 // Return success after mDns reports success
879 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000880 unregisterService(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900881 clientInfo.onRegisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000882 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900883 }
884
Irfan Sheriff75006652012-04-17 23:15:29 -0700885 }
886 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900887 }
888 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800889 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900890 args = (ListenerArgs) msg.obj;
891 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000892 // If the binder death notification for a INsdManagerCallback was received
893 // before any calls are received by NsdService, the clientInfo would be
894 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900895 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800896 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700897 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700898 }
Paul Hud44e1b72023-06-16 02:07:42 +0000899 final ClientRequest request =
900 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900901 if (request == null) {
902 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
903 break;
904 }
Paul Hud44e1b72023-06-16 02:07:42 +0000905 transactionId = request.mTransactionId;
906 removeRequestMap(clientRequestId, transactionId, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900907
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900908 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
909 // so this needs to check the type of the original request to unregister
910 // instead of looking at the flag value.
911 if (request instanceof AdvertiserClientRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +0000912 mAdvertiser.removeService(transactionId);
913 clientInfo.onUnregisterServiceSucceeded(clientRequestId);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700914 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000915 if (unregisterService(transactionId)) {
916 clientInfo.onUnregisterServiceSucceeded(clientRequestId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900917 } else {
918 clientInfo.onUnregisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000919 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900920 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700921 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700922 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900923 }
Paul Hu75069ed2023-01-14 00:31:09 +0800924 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800925 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900926 args = (ListenerArgs) msg.obj;
927 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000928 // If the binder death notification for a INsdManagerCallback was received
929 // before any calls are received by NsdService, the clientInfo would be
930 // cleared and cause NPE. Add a null check here to prevent this corner case.
931 if (clientInfo == null) {
932 Log.e(TAG, "Unknown connector in resolution");
933 break;
934 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700935
Paul Hu75069ed2023-01-14 00:31:09 +0800936 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000937 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900938 final Pair<String, String> typeSubtype =
939 parseTypeAndSubtype(info.getServiceType());
940 final String serviceType = typeSubtype == null
941 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800942 if (clientInfo.mUseJavaBackend
943 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900944 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800945 if (serviceType == null) {
Paul Hud44e1b72023-06-16 02:07:42 +0000946 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu75069ed2023-01-14 00:31:09 +0800947 NsdManager.FAILURE_INTERNAL_ERROR);
948 break;
949 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900950 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +0800951
952 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +0000953 final MdnsListener listener = new ResolutionListener(clientRequestId,
954 transactionId, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800955 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
956 .setNetwork(info.getNetwork())
957 .setIsPassiveMode(true)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900958 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +0900959 .setRemoveExpiredService(true)
Paul Hu75069ed2023-01-14 00:31:09 +0800960 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900961 mMdnsDiscoveryManager.registerListener(
962 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +0000963 storeDiscoveryManagerRequestMap(clientRequestId, transactionId,
964 listener, clientInfo, info.getNetwork());
965 clientInfo.log("Register a ResolutionListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +0000966 + " for service type:" + resolveServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700967 } else {
Paul Hu75069ed2023-01-14 00:31:09 +0800968 if (clientInfo.mResolvedService != null) {
969 clientInfo.onResolveServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000970 clientRequestId, NsdManager.FAILURE_ALREADY_ACTIVE);
Paul Hu75069ed2023-01-14 00:31:09 +0800971 break;
972 }
973
974 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000975 if (resolveService(transactionId, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800976 clientInfo.mResolvedService = new NsdServiceInfo();
Paul Hud44e1b72023-06-16 02:07:42 +0000977 storeLegacyRequestMap(
978 clientRequestId, transactionId, clientInfo, msg.what);
Paul Hu75069ed2023-01-14 00:31:09 +0800979 } else {
980 clientInfo.onResolveServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000981 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu75069ed2023-01-14 00:31:09 +0800982 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700983 }
984 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800985 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900986 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +0000987 if (DBG) Log.d(TAG, "Stop service resolution");
988 args = (ListenerArgs) msg.obj;
989 clientInfo = mClients.get(args.connector);
990 // If the binder death notification for a INsdManagerCallback was received
991 // before any calls are received by NsdService, the clientInfo would be
992 // cleared and cause NPE. Add a null check here to prevent this corner case.
993 if (clientInfo == null) {
994 Log.e(TAG, "Unknown connector in stop resolution");
995 break;
996 }
997
Paul Hud44e1b72023-06-16 02:07:42 +0000998 final ClientRequest request =
999 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001000 if (request == null) {
1001 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
1002 break;
1003 }
Paul Hud44e1b72023-06-16 02:07:42 +00001004 transactionId = request.mTransactionId;
Paul Hue4f5f252023-02-16 21:13:47 +08001005 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
1006 // point, so this needs to check the type of the original request to
1007 // unregister instead of looking at the flag value.
1008 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001009 stopDiscoveryManagerRequest(
1010 request, clientRequestId, transactionId, clientInfo);
1011 clientInfo.onStopResolutionSucceeded(clientRequestId);
1012 clientInfo.log("Unregister the ResolutionListener " + transactionId);
Paul Hub58deb72022-12-26 09:24:42 +00001013 } else {
Paul Hud44e1b72023-06-16 02:07:42 +00001014 removeRequestMap(clientRequestId, transactionId, clientInfo);
1015 if (stopResolveService(transactionId)) {
1016 clientInfo.onStopResolutionSucceeded(clientRequestId);
Paul Hue4f5f252023-02-16 21:13:47 +08001017 } else {
1018 clientInfo.onStopResolutionFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001019 clientRequestId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hue4f5f252023-02-16 21:13:47 +08001020 }
1021 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +00001022 }
Paul Hub58deb72022-12-26 09:24:42 +00001023 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001024 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001025 case NsdManager.REGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001026 if (DBG) Log.d(TAG, "Register a service callback");
1027 args = (ListenerArgs) msg.obj;
1028 clientInfo = mClients.get(args.connector);
1029 // If the binder death notification for a INsdManagerCallback was received
1030 // before any calls are received by NsdService, the clientInfo would be
1031 // cleared and cause NPE. Add a null check here to prevent this corner case.
1032 if (clientInfo == null) {
1033 Log.e(TAG, "Unknown connector in callback registration");
1034 break;
1035 }
1036
Paul Hu30bd70d2023-02-07 13:20:56 +00001037 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001038 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001039 final Pair<String, String> typeAndSubtype =
1040 parseTypeAndSubtype(info.getServiceType());
1041 final String serviceType = typeAndSubtype == null
1042 ? null : typeAndSubtype.first;
Paul Hu30bd70d2023-02-07 13:20:56 +00001043 if (serviceType == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001044 clientInfo.onServiceInfoCallbackRegistrationFailed(clientRequestId,
Paul Hu30bd70d2023-02-07 13:20:56 +00001045 NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +00001046 break;
1047 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001048 final String resolveServiceType = serviceType + ".local";
Paul Hu18aeccc2022-12-27 08:48:48 +00001049
Paul Hu30bd70d2023-02-07 13:20:56 +00001050 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001051 final MdnsListener listener = new ServiceInfoListener(clientRequestId,
1052 transactionId, info, resolveServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +00001053 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1054 .setNetwork(info.getNetwork())
1055 .setIsPassiveMode(true)
1056 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001057 .setRemoveExpiredService(true)
Paul Hu30bd70d2023-02-07 13:20:56 +00001058 .build();
1059 mMdnsDiscoveryManager.registerListener(
1060 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001061 storeDiscoveryManagerRequestMap(clientRequestId, transactionId, listener,
1062 clientInfo, info.getNetwork());
1063 clientInfo.log("Register a ServiceInfoListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001064 + " for service type:" + resolveServiceType);
Paul Hu18aeccc2022-12-27 08:48:48 +00001065 break;
Paul Hu30bd70d2023-02-07 13:20:56 +00001066 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001067 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001068 if (DBG) Log.d(TAG, "Unregister a service callback");
1069 args = (ListenerArgs) msg.obj;
1070 clientInfo = mClients.get(args.connector);
1071 // If the binder death notification for a INsdManagerCallback was received
1072 // before any calls are received by NsdService, the clientInfo would be
1073 // cleared and cause NPE. Add a null check here to prevent this corner case.
1074 if (clientInfo == null) {
1075 Log.e(TAG, "Unknown connector in callback unregistration");
1076 break;
1077 }
1078
Paul Hud44e1b72023-06-16 02:07:42 +00001079 final ClientRequest request =
1080 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001081 if (request == null) {
Paul Hu30bd70d2023-02-07 13:20:56 +00001082 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE_CALLBACK");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001083 break;
1084 }
Paul Hud44e1b72023-06-16 02:07:42 +00001085 transactionId = request.mTransactionId;
Paul Hu30bd70d2023-02-07 13:20:56 +00001086 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001087 stopDiscoveryManagerRequest(
1088 request, clientRequestId, transactionId, clientInfo);
1089 clientInfo.onServiceInfoCallbackUnregistered(clientRequestId);
1090 clientInfo.log("Unregister the ServiceInfoListener " + transactionId);
Paul Hu18aeccc2022-12-27 08:48:48 +00001091 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001092 loge("Unregister failed with non-DiscoveryManagerRequest.");
Paul Hu18aeccc2022-12-27 08:48:48 +00001093 }
Paul Hu18aeccc2022-12-27 08:48:48 +00001094 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001095 }
paulhu2b9ed952022-02-10 21:58:32 +08001096 case MDNS_SERVICE_EVENT:
1097 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +09001098 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001099 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001100 break;
Paul Hu019621e2023-01-13 23:26:49 +08001101 case MDNS_DISCOVERY_MANAGER_EVENT:
1102 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
1103 return NOT_HANDLED;
1104 }
1105 break;
Irfan Sheriff75006652012-04-17 23:15:29 -07001106 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001107 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001108 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001109 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001110 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001111
Paul Hud44e1b72023-06-16 02:07:42 +00001112 private boolean handleMDnsServiceEvent(int code, int transactionId, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001113 NsdServiceInfo servInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001114 ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001115 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001116 Log.e(TAG, String.format(
1117 "transactionId %d for %d has no client mapping", transactionId, code));
Hugo Benichif0c84092017-04-05 14:43:29 +09001118 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001119 }
1120
1121 /* This goes in response as msg.arg2 */
Paul Hud44e1b72023-06-16 02:07:42 +00001122 int clientRequestId = clientInfo.getClientRequestId(transactionId);
1123 if (clientRequestId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -07001124 // This can happen because of race conditions. For example,
1125 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
1126 // and we may get in this situation.
Paul Hud44e1b72023-06-16 02:07:42 +00001127 Log.d(TAG, String.format("%d for transactionId %d that is no longer active",
1128 code, transactionId));
Hugo Benichif0c84092017-04-05 14:43:29 +09001129 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001130 }
Hugo Benichi32be63d2017-04-05 14:06:11 +09001131 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00001132 Log.d(TAG, String.format(
1133 "MDns service event code:%d transactionId=%d", code, transactionId));
Hugo Benichi32be63d2017-04-05 14:06:11 +09001134 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001135 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +08001136 case IMDnsEventListener.SERVICE_FOUND: {
1137 final DiscoveryInfo info = (DiscoveryInfo) obj;
1138 final String name = info.serviceName;
1139 final String type = info.registrationType;
1140 servInfo = new NsdServiceInfo(name, type);
1141 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001142 if (foundNetId == 0L) {
1143 // Ignore services that do not have a Network: they are not usable
1144 // by apps, as they would need privileged permissions to use
1145 // interfaces that do not have an associated Network.
1146 break;
1147 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +09001148 if (foundNetId == INetd.DUMMY_NET_ID) {
1149 // Ignore services on the dummy0 interface: they are only seen when
1150 // discovering locally advertised services, and are not reachable
1151 // through that interface.
1152 break;
1153 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001154 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Paul Hud44e1b72023-06-16 02:07:42 +00001155 clientInfo.onServiceFound(clientRequestId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001156 break;
paulhu2b9ed952022-02-10 21:58:32 +08001157 }
1158 case IMDnsEventListener.SERVICE_LOST: {
1159 final DiscoveryInfo info = (DiscoveryInfo) obj;
1160 final String name = info.serviceName;
1161 final String type = info.registrationType;
1162 final int lostNetId = info.netId;
1163 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001164 // The network could be set to null (netId 0) if it was torn down when the
1165 // service is lost
1166 // TODO: avoid returning null in that case, possibly by remembering
1167 // found services on the same interface index and their network at the time
1168 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Paul Hud44e1b72023-06-16 02:07:42 +00001169 clientInfo.onServiceLost(clientRequestId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001170 break;
paulhu2b9ed952022-02-10 21:58:32 +08001171 }
1172 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001173 clientInfo.onDiscoverServicesFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001174 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001175 break;
paulhu2b9ed952022-02-10 21:58:32 +08001176 case IMDnsEventListener.SERVICE_REGISTERED: {
1177 final RegistrationInfo info = (RegistrationInfo) obj;
1178 final String name = info.serviceName;
1179 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Paul Hud44e1b72023-06-16 02:07:42 +00001180 clientInfo.onRegisterServiceSucceeded(clientRequestId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001181 break;
paulhu2b9ed952022-02-10 21:58:32 +08001182 }
1183 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001184 clientInfo.onRegisterServiceFailed(
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_RESOLVED: {
1188 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001189 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +08001190 final String fullName = info.serviceFullName;
1191 while (index < fullName.length() && fullName.charAt(index) != '.') {
1192 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001193 ++index;
1194 }
1195 ++index;
1196 }
paulhu2b9ed952022-02-10 21:58:32 +08001197 if (index >= fullName.length()) {
1198 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001199 break;
1200 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001201
paulhube186602022-04-12 07:18:23 +00001202 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001203 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001204 String type = rest.replace(".local.", "");
1205
Paul Hu30bd70d2023-02-07 13:20:56 +00001206 final NsdServiceInfo serviceInfo = clientInfo.mResolvedService;
Paul Hu18aeccc2022-12-27 08:48:48 +00001207 serviceInfo.setServiceName(name);
1208 serviceInfo.setServiceType(type);
1209 serviceInfo.setPort(info.port);
1210 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001211 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001212
Paul Hud44e1b72023-06-16 02:07:42 +00001213 stopResolveService(transactionId);
1214 removeRequestMap(clientRequestId, transactionId, clientInfo);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001215
Paul Hud44e1b72023-06-16 02:07:42 +00001216 final int transactionId2 = getUniqueId();
1217 if (getAddrInfo(transactionId2, info.hostname, info.interfaceIdx)) {
1218 storeLegacyRequestMap(clientRequestId, transactionId2, clientInfo,
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001219 NsdManager.RESOLVE_SERVICE);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001220 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001221 clientInfo.onResolveServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001222 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu30bd70d2023-02-07 13:20:56 +00001223 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001224 }
1225 break;
paulhu2b9ed952022-02-10 21:58:32 +08001226 }
1227 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001228 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001229 stopResolveService(transactionId);
1230 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001231 clientInfo.onResolveServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001232 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu30bd70d2023-02-07 13:20:56 +00001233 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001234 break;
paulhu2b9ed952022-02-10 21:58:32 +08001235 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001236 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001237 stopGetAddrInfo(transactionId);
1238 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001239 clientInfo.onResolveServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001240 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu30bd70d2023-02-07 13:20:56 +00001241 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001242 break;
paulhu2b9ed952022-02-10 21:58:32 +08001243 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001244 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001245 final GetAddressInfo info = (GetAddressInfo) obj;
1246 final String address = info.address;
1247 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001248 InetAddress serviceHost = null;
1249 try {
paulhu2b9ed952022-02-10 21:58:32 +08001250 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001251 } catch (UnknownHostException e) {
1252 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1253 }
1254
1255 // If the resolved service is on an interface without a network, consider it
1256 // as a failure: it would not be usable by apps as they would need
1257 // privileged permissions.
Paul Hu30bd70d2023-02-07 13:20:56 +00001258 if (netId != NETID_UNSET && serviceHost != null) {
1259 clientInfo.mResolvedService.setHost(serviceHost);
1260 setServiceNetworkForCallback(clientInfo.mResolvedService,
1261 netId, info.interfaceIdx);
1262 clientInfo.onResolveServiceSucceeded(
Paul Hud44e1b72023-06-16 02:07:42 +00001263 clientRequestId, clientInfo.mResolvedService);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001264 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001265 clientInfo.onResolveServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001266 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001267 }
Paul Hud44e1b72023-06-16 02:07:42 +00001268 stopGetAddrInfo(transactionId);
1269 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001270 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001271 break;
paulhu2b9ed952022-02-10 21:58:32 +08001272 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001273 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001274 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001275 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001276 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001277 }
Paul Hu019621e2023-01-13 23:26:49 +08001278
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001279 @Nullable
1280 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(
1281 final MdnsEvent event, int code) {
Paul Hu019621e2023-01-13 23:26:49 +08001282 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001283 final String[] typeArray = serviceInfo.getServiceType();
1284 final String joinedType;
1285 if (typeArray.length == 0
1286 || !typeArray[typeArray.length - 1].equals(LOCAL_DOMAIN_NAME)) {
1287 Log.wtf(TAG, "MdnsServiceInfo type does not end in .local: "
1288 + Arrays.toString(typeArray));
1289 return null;
1290 } else {
1291 joinedType = TextUtils.join(".",
1292 Arrays.copyOfRange(typeArray, 0, typeArray.length - 1));
1293 }
1294 final String serviceType;
1295 switch (code) {
1296 case NsdManager.SERVICE_FOUND:
1297 case NsdManager.SERVICE_LOST:
1298 // For consistency with historical behavior, discovered service types have
1299 // a dot at the end.
1300 serviceType = joinedType + ".";
1301 break;
1302 case RESOLVE_SERVICE_SUCCEEDED:
1303 // For consistency with historical behavior, resolved service types have
1304 // a dot at the beginning.
1305 serviceType = "." + joinedType;
1306 break;
1307 default:
1308 serviceType = joinedType;
1309 break;
1310 }
Paul Hu019621e2023-01-13 23:26:49 +08001311 final String serviceName = serviceInfo.getServiceInstanceName();
1312 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1313 final Network network = serviceInfo.getNetwork();
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001314 // In MdnsDiscoveryManagerEvent, the Network can be null which means it is a
1315 // network for Tethering interface. In other words, the network == null means the
1316 // network has netId = INetd.LOCAL_NET_ID.
Paul Hu019621e2023-01-13 23:26:49 +08001317 setServiceNetworkForCallback(
1318 servInfo,
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001319 network == null ? INetd.LOCAL_NET_ID : network.netId,
Paul Hu019621e2023-01-13 23:26:49 +08001320 serviceInfo.getInterfaceIndex());
1321 return servInfo;
1322 }
1323
1324 private boolean handleMdnsDiscoveryManagerEvent(
1325 int transactionId, int code, Object obj) {
Paul Hud44e1b72023-06-16 02:07:42 +00001326 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Paul Hu019621e2023-01-13 23:26:49 +08001327 if (clientInfo == null) {
1328 Log.e(TAG, String.format(
1329 "id %d for %d has no client mapping", transactionId, code));
1330 return false;
1331 }
1332
1333 final MdnsEvent event = (MdnsEvent) obj;
Paul Hud44e1b72023-06-16 02:07:42 +00001334 final int clientRequestId = event.mClientRequestId;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001335 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event, code);
1336 // Errors are already logged if null
1337 if (info == null) return false;
Paul Hu83ec7f42023-06-07 18:04:09 +08001338 mServiceLogs.log(String.format(
1339 "MdnsDiscoveryManager event code=%s transactionId=%d",
1340 NsdManager.nameOf(code), transactionId));
Paul Hu019621e2023-01-13 23:26:49 +08001341 switch (code) {
1342 case NsdManager.SERVICE_FOUND:
Paul Hud44e1b72023-06-16 02:07:42 +00001343 clientInfo.onServiceFound(clientRequestId, info);
Paul Hu319751a2023-01-13 23:56:34 +08001344 break;
1345 case NsdManager.SERVICE_LOST:
Paul Hud44e1b72023-06-16 02:07:42 +00001346 clientInfo.onServiceLost(clientRequestId, info);
Paul Hu019621e2023-01-13 23:26:49 +08001347 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001348 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
Paul Hud44e1b72023-06-16 02:07:42 +00001349 final ClientRequest request =
1350 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001351 if (request == null) {
1352 Log.e(TAG, "Unknown client request in RESOLVE_SERVICE_SUCCEEDED");
1353 break;
1354 }
Paul Hu75069ed2023-01-14 00:31:09 +08001355 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Paul Hu75069ed2023-01-14 00:31:09 +08001356 info.setPort(serviceInfo.getPort());
1357
1358 Map<String, String> attrs = serviceInfo.getAttributes();
1359 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1360 final String key = kv.getKey();
1361 try {
1362 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1363 } catch (IllegalArgumentException e) {
1364 Log.e(TAG, "Invalid attribute", e);
1365 }
1366 }
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001367 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu2b865912023-03-06 14:27:53 +08001368 if (addresses.size() != 0) {
1369 info.setHostAddresses(addresses);
Paul Hud44e1b72023-06-16 02:07:42 +00001370 clientInfo.onResolveServiceSucceeded(clientRequestId, info);
Paul Hu2b865912023-03-06 14:27:53 +08001371 } else {
1372 // No address. Notify resolution failure.
Paul Hu75069ed2023-01-14 00:31:09 +08001373 clientInfo.onResolveServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001374 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu75069ed2023-01-14 00:31:09 +08001375 }
1376
1377 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001378 if (!(request instanceof DiscoveryManagerRequest)) {
1379 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1380 break;
1381 }
Paul Hud44e1b72023-06-16 02:07:42 +00001382 stopDiscoveryManagerRequest(
1383 request, clientRequestId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001384 break;
1385 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001386 case NsdManager.SERVICE_UPDATED: {
1387 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1388 info.setPort(serviceInfo.getPort());
1389
1390 Map<String, String> attrs = serviceInfo.getAttributes();
1391 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1392 final String key = kv.getKey();
1393 try {
1394 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1395 } catch (IllegalArgumentException e) {
1396 Log.e(TAG, "Invalid attribute", e);
1397 }
1398 }
1399
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001400 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001401 info.setHostAddresses(addresses);
Paul Hud44e1b72023-06-16 02:07:42 +00001402 clientInfo.onServiceUpdated(clientRequestId, info);
Paul Hu30bd70d2023-02-07 13:20:56 +00001403 break;
1404 }
1405 case NsdManager.SERVICE_UPDATED_LOST:
Paul Hud44e1b72023-06-16 02:07:42 +00001406 clientInfo.onServiceUpdatedLost(clientRequestId);
Paul Hu30bd70d2023-02-07 13:20:56 +00001407 break;
Paul Hu019621e2023-01-13 23:26:49 +08001408 default:
1409 return false;
1410 }
1411 return true;
1412 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001413 }
1414 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001415
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001416 @NonNull
1417 private static List<InetAddress> getInetAddresses(@NonNull MdnsServiceInfo serviceInfo) {
1418 final List<String> v4Addrs = serviceInfo.getIpv4Addresses();
1419 final List<String> v6Addrs = serviceInfo.getIpv6Addresses();
1420 final List<InetAddress> addresses = new ArrayList<>(v4Addrs.size() + v6Addrs.size());
1421 for (String ipv4Address : v4Addrs) {
1422 try {
1423 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1424 } catch (IllegalArgumentException e) {
1425 Log.wtf(TAG, "Invalid ipv4 address", e);
1426 }
1427 }
1428 for (String ipv6Address : v6Addrs) {
1429 try {
Yuyang Huanga6a6ff92023-04-24 13:33:34 +09001430 final Inet6Address addr = (Inet6Address) InetAddresses.parseNumericAddress(
1431 ipv6Address);
1432 addresses.add(InetAddressUtils.withScopeId(addr, serviceInfo.getInterfaceIndex()));
1433 } catch (IllegalArgumentException e) {
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001434 Log.wtf(TAG, "Invalid ipv6 address", e);
1435 }
1436 }
1437 return addresses;
1438 }
1439
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001440 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1441 switch (netId) {
1442 case NETID_UNSET:
1443 info.setNetwork(null);
1444 break;
1445 case INetd.LOCAL_NET_ID:
1446 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1447 // visible / usable for apps, so do not return it. Store the interface
1448 // index instead, so at least if the client tries to resolve the service
1449 // with that NsdServiceInfo, it will be done on the same interface.
1450 // If they recreate the NsdServiceInfo themselves, resolution would be
1451 // done on all interfaces as before T, which should also work.
1452 info.setNetwork(null);
1453 info.setInterfaceIndex(ifaceIdx);
1454 break;
1455 default:
1456 info.setNetwork(new Network(netId));
1457 }
1458 }
1459
paulhube186602022-04-12 07:18:23 +00001460 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1461 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1462 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1463 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1464 private String unescape(String s) {
1465 StringBuilder sb = new StringBuilder(s.length());
1466 for (int i = 0; i < s.length(); ++i) {
1467 char c = s.charAt(i);
1468 if (c == '\\') {
1469 if (++i >= s.length()) {
1470 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1471 break;
1472 }
1473 c = s.charAt(i);
1474 if (c != '.' && c != '\\') {
1475 if (i + 2 >= s.length()) {
1476 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1477 break;
1478 }
1479 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1480 + (s.charAt(i + 2) - '0'));
1481 i += 2;
1482 }
1483 }
1484 sb.append(c);
1485 }
1486 return sb.toString();
1487 }
1488
Paul Hu7445e3d2023-03-03 15:14:00 +08001489 /**
1490 * Check the given service type is valid and construct it to a service type
1491 * which can use for discovery / resolution service.
1492 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001493 * <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 +08001494 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1495 * underscore; they are alphanumerical characters or dashes or underscore, except the
1496 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1497 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001498 * <p>The subtype may also be specified with a comma after the service type, for example
1499 * _type._tcp,_subtype.
1500 *
Paul Hu7445e3d2023-03-03 15:14:00 +08001501 * @param serviceType the request service type for discovery / resolution service
1502 * @return constructed service type or null if the given service type is invalid.
1503 */
1504 @Nullable
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001505 public static Pair<String, String> parseTypeAndSubtype(String serviceType) {
Paul Hu7445e3d2023-03-03 15:14:00 +08001506 if (TextUtils.isEmpty(serviceType)) return null;
1507
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001508 final String typeOrSubtypePattern = "_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]";
Paul Hu7445e3d2023-03-03 15:14:00 +08001509 final Pattern serviceTypePattern = Pattern.compile(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001510 // Optional leading subtype (_subtype._type._tcp)
1511 // (?: xxx) is a non-capturing parenthesis, don't capture the dot
1512 "^(?:(" + typeOrSubtypePattern + ")\\.)?"
1513 // Actual type (_type._tcp.local)
1514 + "(" + typeOrSubtypePattern + "\\._(?:tcp|udp))"
Paul Hu7445e3d2023-03-03 15:14:00 +08001515 // Drop '.' at the end of service type that is compatible with old backend.
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001516 // e.g. allow "_type._tcp.local."
1517 + "\\.?"
1518 // Optional subtype after comma, for "_type._tcp,_subtype" format
1519 + "(?:,(" + typeOrSubtypePattern + "))?"
1520 + "$");
Paul Hu7445e3d2023-03-03 15:14:00 +08001521 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1522 if (!matcher.matches()) return null;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001523 // Use the subtype either at the beginning or after the comma
1524 final String subtype = matcher.group(1) != null ? matcher.group(1) : matcher.group(3);
1525 return new Pair<>(matcher.group(2), subtype);
Paul Hu7445e3d2023-03-03 15:14:00 +08001526 }
1527
Hugo Benichi803a2f02017-04-24 11:35:06 +09001528 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001529 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001530 this(ctx, handler, cleanupDelayMs, new Dependencies());
1531 }
1532
1533 @VisibleForTesting
1534 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001535 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001536 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001537 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001538 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001539 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1540 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001541 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001542
Paul Hu14667de2023-04-17 22:42:47 +08001543 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper(),
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001544 LOGGER.forSubComponent("MdnsSocketProvider"), new SocketRequestMonitor());
Yuyang Huang700778b2023-03-08 16:17:05 +09001545 // Netlink monitor starts on boot, and intentionally never stopped, to ensure that all
1546 // address events are received.
1547 handler.post(mMdnsSocketProvider::startNetLinkMonitor);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001548
1549 // NsdService is started after ActivityManager (startOtherServices in SystemServer, vs.
1550 // startBootstrapServices).
1551 mRunningAppActiveImportanceCutoff = mDeps.getDeviceConfigInt(
1552 MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF,
1553 DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF);
1554 final ActivityManager am = ctx.getSystemService(ActivityManager.class);
1555 am.addOnUidImportanceListener(new UidImportanceListener(handler),
1556 mRunningAppActiveImportanceCutoff);
1557
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001558 mMdnsSocketClient =
1559 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider);
Paul Hu14667de2023-04-17 22:42:47 +08001560 mMdnsDiscoveryManager = deps.makeMdnsDiscoveryManager(new ExecutorProvider(),
Yuyang Huang243d1a52023-05-23 17:26:52 +09001561 mMdnsSocketClient, LOGGER.forSubComponent("MdnsDiscoveryManager"));
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001562 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1563 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
Paul Hu14667de2023-04-17 22:42:47 +08001564 new AdvertiserCallback(), LOGGER.forSubComponent("MdnsAdvertiser"));
Paul Hu4bd98ef2023-01-12 13:42:07 +08001565 }
1566
1567 /**
1568 * Dependencies of NsdService, for injection in tests.
1569 */
1570 @VisibleForTesting
1571 public static class Dependencies {
1572 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001573 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001574 *
1575 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001576 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001577 */
1578 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi278db582023-04-21 12:35:22 +09001579 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1580 MDNS_DISCOVERY_MANAGER_VERSION, DeviceConfigUtils.TETHERING_MODULE_NAME,
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +09001581 false /* defaultEnabled */);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001582 }
1583
1584 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001585 * Check whether the MdnsAdvertiser feature is enabled.
1586 *
1587 * @param context The global context information about an app environment.
1588 * @return true if the MdnsAdvertiser feature is enabled.
1589 */
1590 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi278db582023-04-21 12:35:22 +09001591 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1592 MDNS_ADVERTISER_VERSION, DeviceConfigUtils.TETHERING_MODULE_NAME,
1593 false /* defaultEnabled */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001594 }
1595
1596 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001597 * Get the type allowlist flag value.
1598 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1599 */
1600 @Nullable
1601 public String getTypeAllowlistFlags() {
1602 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1603 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1604 }
1605
1606 /**
1607 * @see DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)
1608 */
1609 public boolean isFeatureEnabled(Context context, String feature) {
1610 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1611 feature, DeviceConfigUtils.TETHERING_MODULE_NAME, false /* defaultEnabled */);
1612 }
1613
1614 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001615 * @see MdnsDiscoveryManager
1616 */
1617 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
Paul Hu14667de2023-04-17 22:42:47 +08001618 @NonNull ExecutorProvider executorProvider,
Yuyang Huang243d1a52023-05-23 17:26:52 +09001619 @NonNull MdnsMultinetworkSocketClient socketClient, @NonNull SharedLog sharedLog) {
1620 return new MdnsDiscoveryManager(executorProvider, socketClient, sharedLog);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001621 }
1622
1623 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001624 * @see MdnsAdvertiser
1625 */
1626 public MdnsAdvertiser makeMdnsAdvertiser(
1627 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
Paul Hu14667de2023-04-17 22:42:47 +08001628 @NonNull MdnsAdvertiser.AdvertiserCallback cb, @NonNull SharedLog sharedLog) {
1629 return new MdnsAdvertiser(looper, socketProvider, cb, sharedLog);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001630 }
1631
1632 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001633 * @see MdnsSocketProvider
1634 */
Paul Hu14667de2023-04-17 22:42:47 +08001635 public MdnsSocketProvider makeMdnsSocketProvider(@NonNull Context context,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001636 @NonNull Looper looper, @NonNull SharedLog sharedLog,
1637 @NonNull MdnsSocketProvider.SocketRequestMonitor socketCreationCallback) {
1638 return new MdnsSocketProvider(context, looper, sharedLog, socketCreationCallback);
1639 }
1640
1641 /**
1642 * @see DeviceConfig#getInt(String, String, int)
1643 */
1644 public int getDeviceConfigInt(@NonNull String config, int defaultValue) {
1645 return DeviceConfig.getInt(NAMESPACE_TETHERING, config, defaultValue);
1646 }
1647
1648 /**
1649 * @see Binder#getCallingUid()
1650 */
1651 public int getCallingUid() {
1652 return Binder.getCallingUid();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001653 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001654 }
1655
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001656 /**
1657 * Return whether a type is allowlisted to use the Java backend.
1658 * @param type The service type
1659 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1660 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1661 */
1662 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1663 @NonNull String flagPrefix) {
1664 if (type == null) return false;
1665 final String typesConfig = mDeps.getTypeAllowlistFlags();
1666 if (TextUtils.isEmpty(typesConfig)) return false;
1667
1668 final String mappingPrefix = type + ":";
1669 String mappedFlag = null;
1670 for (String mapping : TextUtils.split(typesConfig, ",")) {
1671 if (mapping.startsWith(mappingPrefix)) {
1672 mappedFlag = mapping.substring(mappingPrefix.length());
1673 break;
1674 }
1675 }
1676
1677 if (mappedFlag == null) return false;
1678
1679 return mDeps.isFeatureEnabled(mContext,
1680 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1681 }
1682
1683 private boolean useDiscoveryManagerForType(@Nullable String type) {
1684 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1685 }
1686
1687 private boolean useAdvertiserForType(@Nullable String type) {
1688 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1689 }
1690
paulhu1b35e822022-04-08 14:48:41 +08001691 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001692 HandlerThread thread = new HandlerThread(TAG);
1693 thread.start();
1694 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001695 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001696 return service;
1697 }
1698
paulhu2b9ed952022-02-10 21:58:32 +08001699 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1700 private final StateMachine mStateMachine;
1701
1702 MDnsEventCallback(StateMachine sm) {
1703 mStateMachine = sm;
1704 }
1705
1706 @Override
1707 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1708 mStateMachine.sendMessage(
1709 MDNS_SERVICE_EVENT, status.result, status.id, status);
1710 }
1711
1712 @Override
1713 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1714 mStateMachine.sendMessage(
1715 MDNS_SERVICE_EVENT, status.result, status.id, status);
1716 }
1717
1718 @Override
1719 public void onServiceResolutionStatus(final ResolutionInfo status) {
1720 mStateMachine.sendMessage(
1721 MDNS_SERVICE_EVENT, status.result, status.id, status);
1722 }
1723
1724 @Override
1725 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1726 mStateMachine.sendMessage(
1727 MDNS_SERVICE_EVENT, status.result, status.id, status);
1728 }
1729
1730 @Override
1731 public int getInterfaceVersion() throws RemoteException {
1732 return this.VERSION;
1733 }
1734
1735 @Override
1736 public String getInterfaceHash() throws RemoteException {
1737 return this.HASH;
1738 }
1739 }
1740
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001741 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
1742 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001743 public void onRegisterServiceSucceeded(int transactionId, NsdServiceInfo registeredInfo) {
1744 mServiceLogs.log("onRegisterServiceSucceeded: transactionId " + transactionId);
1745 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001746 if (clientInfo == null) return;
1747
Paul Hud44e1b72023-06-16 02:07:42 +00001748 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1749 if (clientRequestId < 0) return;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001750
1751 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1752 // historical behavior.
1753 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
Paul Hud44e1b72023-06-16 02:07:42 +00001754 clientInfo.onRegisterServiceSucceeded(clientRequestId, cbInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001755 }
1756
1757 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001758 public void onRegisterServiceFailed(int transactionId, int errorCode) {
1759 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001760 if (clientInfo == null) return;
1761
Paul Hud44e1b72023-06-16 02:07:42 +00001762 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1763 if (clientRequestId < 0) return;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001764
Paul Hud44e1b72023-06-16 02:07:42 +00001765 clientInfo.onRegisterServiceFailed(clientRequestId, errorCode);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001766 }
1767
Paul Hud44e1b72023-06-16 02:07:42 +00001768 private ClientInfo getClientInfoOrLog(int transactionId) {
1769 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001770 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001771 Log.e(TAG, String.format("Callback for service %d has no client", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001772 }
1773 return clientInfo;
1774 }
1775
Paul Hud44e1b72023-06-16 02:07:42 +00001776 private int getClientRequestIdOrLog(@NonNull ClientInfo info, int transactionId) {
1777 final int clientRequestId = info.getClientRequestId(transactionId);
1778 if (clientRequestId < 0) {
1779 Log.e(TAG, String.format(
1780 "Client request ID not found for service %d", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001781 }
Paul Hud44e1b72023-06-16 02:07:42 +00001782 return clientRequestId;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001783 }
1784 }
1785
Paul Hu2e0a88c2023-03-09 16:05:01 +08001786 private static class ConnectorArgs {
1787 @NonNull public final NsdServiceConnector connector;
1788 @NonNull public final INsdManagerCallback callback;
1789 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001790 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001791
1792 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00001793 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08001794 this.connector = connector;
1795 this.callback = callback;
1796 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001797 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001798 }
1799 }
1800
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001801 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08001802 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001803 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu2e0a88c2023-03-09 16:05:01 +08001804 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001805 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00001806 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
1807 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001808 mDeps.getCallingUid())));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001809 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07001810 }
1811
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001812 private static class ListenerArgs {
1813 public final NsdServiceConnector connector;
1814 public final NsdServiceInfo serviceInfo;
1815 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
1816 this.connector = connector;
1817 this.serviceInfo = serviceInfo;
1818 }
1819 }
1820
1821 private class NsdServiceConnector extends INsdServiceConnector.Stub
1822 implements IBinder.DeathRecipient {
1823 @Override
1824 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
1825 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1826 NsdManager.REGISTER_SERVICE, 0, listenerKey,
1827 new ListenerArgs(this, serviceInfo)));
1828 }
1829
1830 @Override
1831 public void unregisterService(int listenerKey) {
1832 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1833 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
1834 new ListenerArgs(this, null)));
1835 }
1836
1837 @Override
1838 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
1839 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1840 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
1841 new ListenerArgs(this, serviceInfo)));
1842 }
1843
1844 @Override
1845 public void stopDiscovery(int listenerKey) {
1846 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1847 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
1848 }
1849
1850 @Override
1851 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
1852 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1853 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
1854 new ListenerArgs(this, serviceInfo)));
1855 }
1856
1857 @Override
Paul Hub58deb72022-12-26 09:24:42 +00001858 public void stopResolution(int listenerKey) {
1859 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1860 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
1861 }
1862
1863 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00001864 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
1865 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1866 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
1867 new ListenerArgs(this, serviceInfo)));
1868 }
1869
1870 @Override
1871 public void unregisterServiceInfoCallback(int listenerKey) {
1872 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1873 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
1874 new ListenerArgs(this, null)));
1875 }
1876
1877 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001878 public void startDaemon() {
1879 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1880 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
1881 }
1882
1883 @Override
1884 public void binderDied() {
1885 mNsdStateMachine.sendMessage(
1886 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
1887 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001888 }
1889
Hugo Benichi912db992017-04-24 16:41:03 +09001890 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07001891 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07001892 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09001893 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
1894 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07001895 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07001896 }
1897
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001898 private int getUniqueId() {
1899 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
1900 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001901 }
1902
Paul Hud44e1b72023-06-16 02:07:42 +00001903 private boolean registerService(int transactionId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09001904 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00001905 Log.d(TAG, "registerService: " + transactionId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001906 }
Hugo Benichi6d706442017-04-24 16:19:58 +09001907 String name = service.getServiceName();
1908 String type = service.getServiceType();
1909 int port = service.getPort();
1910 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001911 final int registerInterface = getNetworkInterfaceIndex(service);
1912 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08001913 Log.e(TAG, "Interface to register service on not found");
1914 return false;
1915 }
Paul Hud44e1b72023-06-16 02:07:42 +00001916 return mMDnsManager.registerService(
1917 transactionId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001918 }
1919
Paul Hud44e1b72023-06-16 02:07:42 +00001920 private boolean unregisterService(int transactionId) {
1921 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001922 }
1923
Paul Hud44e1b72023-06-16 02:07:42 +00001924 private boolean discoverServices(int transactionId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08001925 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001926 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
1927 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001928 Log.e(TAG, "Interface to discover service on not found");
1929 return false;
1930 }
Paul Hud44e1b72023-06-16 02:07:42 +00001931 return mMDnsManager.discover(transactionId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001932 }
1933
Paul Hud44e1b72023-06-16 02:07:42 +00001934 private boolean stopServiceDiscovery(int transactionId) {
1935 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001936 }
1937
Paul Hud44e1b72023-06-16 02:07:42 +00001938 private boolean resolveService(int transactionId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001939 final String name = service.getServiceName();
1940 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001941 final int resolveInterface = getNetworkInterfaceIndex(service);
1942 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001943 Log.e(TAG, "Interface to resolve service on not found");
1944 return false;
1945 }
Paul Hud44e1b72023-06-16 02:07:42 +00001946 return mMDnsManager.resolve(transactionId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001947 }
1948
1949 /**
1950 * Guess the interface to use to resolve or discover a service on a specific network.
1951 *
1952 * This is an imperfect guess, as for example the network may be gone or not yet fully
1953 * registered. This is fine as failing is correct if the network is gone, and a client
1954 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
1955 * this is to support the legacy mdnsresponder implementation, which historically resolved
1956 * services on an unspecified network.
1957 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001958 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
1959 final Network network = serviceInfo.getNetwork();
1960 if (network == null) {
1961 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
1962 // provided by NsdService from discovery results, and the service was found on an
1963 // interface that has no app-usable Network).
1964 if (serviceInfo.getInterfaceIndex() != 0) {
1965 return serviceInfo.getInterfaceIndex();
1966 }
1967 return IFACE_IDX_ANY;
1968 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001969
1970 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
1971 if (cm == null) {
1972 Log.wtf(TAG, "No ConnectivityManager for resolveService");
1973 return IFACE_IDX_ANY;
1974 }
1975 final LinkProperties lp = cm.getLinkProperties(network);
1976 if (lp == null) return IFACE_IDX_ANY;
1977
1978 // Only resolve on non-stacked interfaces
1979 final NetworkInterface iface;
1980 try {
1981 iface = NetworkInterface.getByName(lp.getInterfaceName());
1982 } catch (SocketException e) {
1983 Log.e(TAG, "Error querying interface", e);
1984 return IFACE_IDX_ANY;
1985 }
1986
1987 if (iface == null) {
1988 Log.e(TAG, "Interface not found: " + lp.getInterfaceName());
1989 return IFACE_IDX_ANY;
1990 }
1991
1992 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001993 }
1994
Paul Hud44e1b72023-06-16 02:07:42 +00001995 private boolean stopResolveService(int transactionId) {
1996 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001997 }
1998
Paul Hud44e1b72023-06-16 02:07:42 +00001999 private boolean getAddrInfo(int transactionId, String hostname, int interfaceIdx) {
2000 return mMDnsManager.getServiceAddress(transactionId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002001 }
2002
Paul Hud44e1b72023-06-16 02:07:42 +00002003 private boolean stopGetAddrInfo(int transactionId) {
2004 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002005 }
2006
2007 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00002008 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2009 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002010
Paul Hub2e67d32023-04-18 05:50:14 +00002011 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2012 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07002013 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00002014
2015 // Dump service and clients logs
2016 pw.println();
Paul Hu14667de2023-04-17 22:42:47 +08002017 pw.println("Logs:");
Paul Hub2e67d32023-04-18 05:50:14 +00002018 pw.increaseIndent();
2019 mServiceLogs.reverseDump(pw);
2020 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002021 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002022
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002023 private abstract static class ClientRequest {
Paul Hud44e1b72023-06-16 02:07:42 +00002024 private final int mTransactionId;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002025
Paul Hud44e1b72023-06-16 02:07:42 +00002026 private ClientRequest(int transactionId) {
2027 mTransactionId = transactionId;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002028 }
2029 }
2030
2031 private static class LegacyClientRequest extends ClientRequest {
2032 private final int mRequestCode;
2033
Paul Hud44e1b72023-06-16 02:07:42 +00002034 private LegacyClientRequest(int transactionId, int requestCode) {
2035 super(transactionId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002036 mRequestCode = requestCode;
2037 }
2038 }
2039
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002040 private abstract static class JavaBackendClientRequest extends ClientRequest {
2041 @Nullable
2042 private final Network mRequestedNetwork;
2043
Paul Hud44e1b72023-06-16 02:07:42 +00002044 private JavaBackendClientRequest(int transactionId, @Nullable Network requestedNetwork) {
2045 super(transactionId);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002046 mRequestedNetwork = requestedNetwork;
2047 }
2048
2049 @Nullable
2050 public Network getRequestedNetwork() {
2051 return mRequestedNetwork;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002052 }
2053 }
2054
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002055 private static class AdvertiserClientRequest extends JavaBackendClientRequest {
Paul Hud44e1b72023-06-16 02:07:42 +00002056 private AdvertiserClientRequest(int transactionId, @Nullable Network requestedNetwork) {
2057 super(transactionId, requestedNetwork);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002058 }
2059 }
2060
2061 private static class DiscoveryManagerRequest extends JavaBackendClientRequest {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002062 @NonNull
2063 private final MdnsListener mListener;
2064
Paul Hud44e1b72023-06-16 02:07:42 +00002065 private DiscoveryManagerRequest(int transactionId, @NonNull MdnsListener listener,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002066 @Nullable Network requestedNetwork) {
Paul Hud44e1b72023-06-16 02:07:42 +00002067 super(transactionId, requestedNetwork);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002068 mListener = listener;
2069 }
2070 }
2071
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002072 /* Information tracked per client */
2073 private class ClientInfo {
2074
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002075 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002076 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002077 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002078 private NsdServiceInfo mResolvedService;
2079
Paul Hud44e1b72023-06-16 02:07:42 +00002080 /* A map from client request ID (listenerKey) to the request */
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002081 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08002082
Luke Huangf7277ed2021-07-12 21:15:10 +08002083 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002084 private boolean mIsPreSClient = false;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002085 private final int mUid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002086 // The flag of using java backend if the client's target SDK >= U
2087 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002088 // Store client logs
2089 private final SharedLog mClientLogs;
Luke Huangf7277ed2021-07-12 21:15:10 +08002090
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002091 private ClientInfo(INsdManagerCallback cb, int uid, boolean useJavaBackend,
2092 SharedLog sharedLog) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002093 mCb = cb;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002094 mUid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002095 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002096 mClientLogs = sharedLog;
2097 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002098 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002099
2100 @Override
2101 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06002102 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07002103 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002104 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002105 sb.append("mUseJavaBackend ").append(mUseJavaBackend).append("\n");
2106 sb.append("mUid ").append(mUid).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002107 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002108 int clientRequestId = mClientRequests.keyAt(i);
2109 sb.append("clientRequestId ")
2110 .append(clientRequestId)
2111 .append(" transactionId ").append(mClientRequests.valueAt(i).mTransactionId)
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002112 .append(" type ").append(
2113 mClientRequests.valueAt(i).getClass().getSimpleName())
2114 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07002115 }
2116 return sb.toString();
2117 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002118
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002119 private boolean isPreSClient() {
2120 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08002121 }
2122
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002123 private void setPreSClient() {
2124 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08002125 }
2126
Paul Hue4f5f252023-02-16 21:13:47 +08002127 private void unregisterMdnsListenerFromRequest(ClientRequest request) {
2128 final MdnsListener listener =
2129 ((DiscoveryManagerRequest) request).mListener;
2130 mMdnsDiscoveryManager.unregisterListener(
2131 listener.getListenedServiceType(), listener);
2132 }
2133
Dave Plattfeff2af2014-03-07 14:48:22 -08002134 // Remove any pending requests from the global map when we get rid of a client,
2135 // and send cancellations to the daemon.
2136 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00002137 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09002138 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002139 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002140 final int clientRequestId = mClientRequests.keyAt(i);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002141 final ClientRequest request = mClientRequests.valueAt(i);
Paul Hud44e1b72023-06-16 02:07:42 +00002142 final int transactionId = request.mTransactionId;
2143 mTransactionIdToClientInfoMap.remove(transactionId);
paulhub2225702021-11-17 09:35:33 +08002144 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002145 Log.d(TAG, "Terminating clientRequestId " + clientRequestId
2146 + " transactionId " + transactionId
2147 + " type " + mClientRequests.get(clientRequestId));
paulhub2225702021-11-17 09:35:33 +08002148 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002149
2150 if (request instanceof DiscoveryManagerRequest) {
Paul Hue4f5f252023-02-16 21:13:47 +08002151 unregisterMdnsListenerFromRequest(request);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002152 continue;
2153 }
2154
2155 if (request instanceof AdvertiserClientRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00002156 mAdvertiser.removeService(transactionId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002157 continue;
2158 }
2159
2160 if (!(request instanceof LegacyClientRequest)) {
2161 throw new IllegalStateException("Unknown request type: " + request.getClass());
2162 }
2163
2164 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08002165 case NsdManager.DISCOVER_SERVICES:
Paul Hud44e1b72023-06-16 02:07:42 +00002166 stopServiceDiscovery(transactionId);
Dave Plattfeff2af2014-03-07 14:48:22 -08002167 break;
2168 case NsdManager.RESOLVE_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002169 stopResolveService(transactionId);
Dave Plattfeff2af2014-03-07 14:48:22 -08002170 break;
2171 case NsdManager.REGISTER_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002172 unregisterService(transactionId);
Dave Plattfeff2af2014-03-07 14:48:22 -08002173 break;
2174 default:
2175 break;
2176 }
2177 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002178 mClientRequests.clear();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002179 updateMulticastLock();
2180 }
2181
2182 /**
2183 * Returns true if this client has any Java backend request that requests one of the given
2184 * networks.
2185 */
2186 boolean hasAnyJavaBackendRequestForNetworks(@NonNull ArraySet<Network> networks) {
2187 for (int i = 0; i < mClientRequests.size(); i++) {
2188 final ClientRequest req = mClientRequests.valueAt(i);
2189 if (!(req instanceof JavaBackendClientRequest)) {
2190 continue;
2191 }
2192 final Network reqNetwork = ((JavaBackendClientRequest) mClientRequests.valueAt(i))
2193 .getRequestedNetwork();
2194 if (MdnsUtils.isAnyNetworkMatched(reqNetwork, networks)) {
2195 return true;
2196 }
2197 }
2198 return false;
Dave Plattfeff2af2014-03-07 14:48:22 -08002199 }
2200
Paul Hud44e1b72023-06-16 02:07:42 +00002201 // mClientRequests is a sparse array of client request id -> ClientRequest. For a given
2202 // transaction id, return the corresponding client request id.
2203 private int getClientRequestId(final int transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002204 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002205 if (mClientRequests.valueAt(i).mTransactionId == transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002206 return mClientRequests.keyAt(i);
2207 }
Christopher Lane74411222014-04-25 18:39:07 -07002208 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002209 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07002210 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002211
Paul Hub2e67d32023-04-18 05:50:14 +00002212 private void log(String message) {
2213 mClientLogs.log(message);
2214 }
2215
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002216 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info) {
2217 try {
2218 mCb.onDiscoverServicesStarted(listenerKey, info);
2219 } catch (RemoteException e) {
2220 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
2221 }
2222 }
2223
2224 void onDiscoverServicesFailed(int listenerKey, int error) {
2225 try {
2226 mCb.onDiscoverServicesFailed(listenerKey, error);
2227 } catch (RemoteException e) {
2228 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
2229 }
2230 }
2231
2232 void onServiceFound(int listenerKey, NsdServiceInfo info) {
2233 try {
2234 mCb.onServiceFound(listenerKey, info);
2235 } catch (RemoteException e) {
2236 Log.e(TAG, "Error calling onServiceFound(", e);
2237 }
2238 }
2239
2240 void onServiceLost(int listenerKey, NsdServiceInfo info) {
2241 try {
2242 mCb.onServiceLost(listenerKey, info);
2243 } catch (RemoteException e) {
2244 Log.e(TAG, "Error calling onServiceLost(", e);
2245 }
2246 }
2247
2248 void onStopDiscoveryFailed(int listenerKey, int error) {
2249 try {
2250 mCb.onStopDiscoveryFailed(listenerKey, error);
2251 } catch (RemoteException e) {
2252 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
2253 }
2254 }
2255
2256 void onStopDiscoverySucceeded(int listenerKey) {
2257 try {
2258 mCb.onStopDiscoverySucceeded(listenerKey);
2259 } catch (RemoteException e) {
2260 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2261 }
2262 }
2263
2264 void onRegisterServiceFailed(int listenerKey, int error) {
2265 try {
2266 mCb.onRegisterServiceFailed(listenerKey, error);
2267 } catch (RemoteException e) {
2268 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2269 }
2270 }
2271
2272 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info) {
2273 try {
2274 mCb.onRegisterServiceSucceeded(listenerKey, info);
2275 } catch (RemoteException e) {
2276 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2277 }
2278 }
2279
2280 void onUnregisterServiceFailed(int listenerKey, int error) {
2281 try {
2282 mCb.onUnregisterServiceFailed(listenerKey, error);
2283 } catch (RemoteException e) {
2284 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2285 }
2286 }
2287
2288 void onUnregisterServiceSucceeded(int listenerKey) {
2289 try {
2290 mCb.onUnregisterServiceSucceeded(listenerKey);
2291 } catch (RemoteException e) {
2292 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2293 }
2294 }
2295
2296 void onResolveServiceFailed(int listenerKey, int error) {
2297 try {
2298 mCb.onResolveServiceFailed(listenerKey, error);
2299 } catch (RemoteException e) {
2300 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2301 }
2302 }
2303
2304 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info) {
2305 try {
2306 mCb.onResolveServiceSucceeded(listenerKey, info);
2307 } catch (RemoteException e) {
2308 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2309 }
2310 }
Paul Hub58deb72022-12-26 09:24:42 +00002311
2312 void onStopResolutionFailed(int listenerKey, int error) {
2313 try {
2314 mCb.onStopResolutionFailed(listenerKey, error);
2315 } catch (RemoteException e) {
2316 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2317 }
2318 }
2319
2320 void onStopResolutionSucceeded(int listenerKey) {
2321 try {
2322 mCb.onStopResolutionSucceeded(listenerKey);
2323 } catch (RemoteException e) {
2324 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2325 }
2326 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002327
2328 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
2329 try {
2330 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2331 } catch (RemoteException e) {
2332 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2333 }
2334 }
2335
2336 void onServiceUpdated(int listenerKey, NsdServiceInfo info) {
2337 try {
2338 mCb.onServiceUpdated(listenerKey, info);
2339 } catch (RemoteException e) {
2340 Log.e(TAG, "Error calling onServiceUpdated", e);
2341 }
2342 }
2343
2344 void onServiceUpdatedLost(int listenerKey) {
2345 try {
2346 mCb.onServiceUpdatedLost(listenerKey);
2347 } catch (RemoteException e) {
2348 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2349 }
2350 }
2351
2352 void onServiceInfoCallbackUnregistered(int listenerKey) {
2353 try {
2354 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2355 } catch (RemoteException e) {
2356 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2357 }
2358 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002359 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002360}