blob: f30f12004f8fde812f062990a924382ff3c47d39 [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;
Paul Hu019621e2023-01-13 23:26:49 +080020import static android.net.nsd.NsdManager.MDNS_DISCOVERY_MANAGER_EVENT;
paulhu2b9ed952022-02-10 21:58:32 +080021import static android.net.nsd.NsdManager.MDNS_SERVICE_EVENT;
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +090022import static android.provider.DeviceConfig.NAMESPACE_TETHERING;
paulhu2b9ed952022-02-10 21:58:32 +080023
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090024import static com.android.modules.utils.build.SdkLevel.isAtLeastU;
Yuyang Huangde802c82023-05-02 17:14:22 +090025import static com.android.server.connectivity.mdns.MdnsRecord.MAX_LABEL_LENGTH;
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090026
Paul Hu23fa2022023-01-13 22:57:24 +080027import android.annotation.NonNull;
Paul Hu4bd98ef2023-01-12 13:42:07 +080028import android.annotation.Nullable;
paulhua262cc12019-08-12 16:25:11 +080029import android.content.Context;
Irfan Sheriff75006652012-04-17 23:15:29 -070030import android.content.Intent;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090031import android.net.ConnectivityManager;
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +090032import android.net.INetd;
Paul Hu75069ed2023-01-14 00:31:09 +080033import android.net.InetAddresses;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090034import android.net.LinkProperties;
35import android.net.Network;
paulhu2b9ed952022-02-10 21:58:32 +080036import android.net.mdns.aidl.DiscoveryInfo;
37import android.net.mdns.aidl.GetAddressInfo;
38import android.net.mdns.aidl.IMDnsEventListener;
39import android.net.mdns.aidl.RegistrationInfo;
40import android.net.mdns.aidl.ResolutionInfo;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070041import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090042import android.net.nsd.INsdManagerCallback;
43import android.net.nsd.INsdServiceConnector;
paulhu2b9ed952022-02-10 21:58:32 +080044import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070045import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080046import android.net.nsd.NsdServiceInfo;
Paul Hub2e67d32023-04-18 05:50:14 +000047import android.os.Binder;
Hugo Benichi803a2f02017-04-24 11:35:06 +090048import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080049import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090050import android.os.IBinder;
Paul Hu4bd98ef2023-01-12 13:42:07 +080051import android.os.Looper;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070052import android.os.Message;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090053import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070054import android.os.UserHandle;
Paul Hu23fa2022023-01-13 22:57:24 +080055import android.text.TextUtils;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090056import android.util.Log;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070057import android.util.SparseArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070058
paulhua262cc12019-08-12 16:25:11 +080059import com.android.internal.annotations.VisibleForTesting;
Paul Hub2e67d32023-04-18 05:50:14 +000060import com.android.internal.util.IndentingPrintWriter;
paulhua262cc12019-08-12 16:25:11 +080061import com.android.internal.util.State;
62import com.android.internal.util.StateMachine;
Paul Hu4bd98ef2023-01-12 13:42:07 +080063import com.android.net.module.util.DeviceConfigUtils;
Yuyang Huanga6a6ff92023-04-24 13:33:34 +090064import com.android.net.module.util.InetAddressUtils;
paulhu3ffffe72021-09-16 10:15:22 +080065import com.android.net.module.util.PermissionUtils;
Paul Hub2e67d32023-04-18 05:50:14 +000066import com.android.net.module.util.SharedLog;
Paul Hu4bd98ef2023-01-12 13:42:07 +080067import com.android.server.connectivity.mdns.ExecutorProvider;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090068import com.android.server.connectivity.mdns.MdnsAdvertiser;
Paul Hu4bd98ef2023-01-12 13:42:07 +080069import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
70import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
Paul Hu23fa2022023-01-13 22:57:24 +080071import com.android.server.connectivity.mdns.MdnsSearchOptions;
72import com.android.server.connectivity.mdns.MdnsServiceBrowserListener;
73import com.android.server.connectivity.mdns.MdnsServiceInfo;
Paul Hu4bd98ef2023-01-12 13:42:07 +080074import com.android.server.connectivity.mdns.MdnsSocketClientBase;
75import com.android.server.connectivity.mdns.MdnsSocketProvider;
Yuyang Huangde802c82023-05-02 17:14:22 +090076import com.android.server.connectivity.mdns.util.MdnsUtils;
paulhua262cc12019-08-12 16:25:11 +080077
Irfan Sheriff77ec5582012-03-22 17:01:39 -070078import java.io.FileDescriptor;
79import java.io.PrintWriter;
Yuyang Huangaa0e9602023-03-17 12:43:09 +090080import java.net.Inet6Address;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070081import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090082import java.net.NetworkInterface;
83import java.net.SocketException;
84import java.net.UnknownHostException;
Paul Hu2b865912023-03-06 14:27:53 +080085import java.util.ArrayList;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070086import java.util.HashMap;
Paul Hu23fa2022023-01-13 22:57:24 +080087import java.util.List;
Paul Hu75069ed2023-01-14 00:31:09 +080088import java.util.Map;
Paul Hu23fa2022023-01-13 22:57:24 +080089import java.util.regex.Matcher;
90import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070091
Irfan Sheriff77ec5582012-03-22 17:01:39 -070092/**
93 * Network Service Discovery Service handles remote service discovery operation requests by
94 * implementing the INsdManager interface.
95 *
96 * @hide
97 */
98public class NsdService extends INsdManager.Stub {
99 private static final String TAG = "NsdService";
100 private static final String MDNS_TAG = "mDnsConnector";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900101 /**
102 * Enable discovery using the Java DiscoveryManager, instead of the legacy mdnsresponder
103 * implementation.
104 */
Paul Hu4bd98ef2023-01-12 13:42:07 +0800105 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +0800106 private static final String LOCAL_DOMAIN_NAME = "local";
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700107
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900108 /**
109 * Enable advertising using the Java MdnsAdvertiser, instead of the legacy mdnsresponder
110 * implementation.
111 */
112 private static final String MDNS_ADVERTISER_VERSION = "mdns_advertiser_version";
113
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900114 /**
115 * Comma-separated list of type:flag mappings indicating the flags to use to allowlist
116 * discovery/advertising using MdnsDiscoveryManager / MdnsAdvertiser for a given type.
117 *
118 * For example _mytype._tcp.local and _othertype._tcp.local would be configured with:
119 * _mytype._tcp:mytype,_othertype._tcp.local:othertype
120 *
121 * In which case the flags:
122 * "mdns_discovery_manager_allowlist_mytype_version",
123 * "mdns_advertiser_allowlist_mytype_version",
124 * "mdns_discovery_manager_allowlist_othertype_version",
125 * "mdns_advertiser_allowlist_othertype_version"
126 * would be used to toggle MdnsDiscoveryManager / MdnsAdvertiser for each type. The flags will
127 * be read with
128 * {@link DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)}.
129 *
130 * @see #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX
131 * @see #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX
132 * @see #MDNS_ALLOWLIST_FLAG_SUFFIX
133 */
134 private static final String MDNS_TYPE_ALLOWLIST_FLAGS = "mdns_type_allowlist_flags";
135
136 private static final String MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX =
137 "mdns_discovery_manager_allowlist_";
138 private static final String MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX =
139 "mdns_advertiser_allowlist_";
140 private static final String MDNS_ALLOWLIST_FLAG_SUFFIX = "_version";
141
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900142 public static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +0000143 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900144 private static final int IFACE_IDX_ANY = 0;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700145
Hugo Benichi32be63d2017-04-05 14:06:11 +0900146 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900147 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +0800148 private final MDnsManager mMDnsManager;
149 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900150 @NonNull
151 private final Dependencies mDeps;
152 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800153 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900154 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800155 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900156 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800157 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900158 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900159 private final MdnsAdvertiser mAdvertiser;
Paul Hub2e67d32023-04-18 05:50:14 +0000160 private final SharedLog mServiceLogs = new SharedLog(TAG);
Paul Hu23fa2022023-01-13 22:57:24 +0800161 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800162 // state machine thread. If change this outside state machine, it will need to introduce
163 // synchronization.
164 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800165 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700166
167 /**
168 * Clients receiving asynchronous messages
169 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900170 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700171
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700172 /* A map from unique id to client info */
Hugo Benichi32be63d2017-04-05 14:06:11 +0900173 private final SparseArray<ClientInfo> mIdToClientInfoMap= new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700174
Luke Huang05298582021-06-13 16:52:05 +0000175 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700176
Hugo Benichi32be63d2017-04-05 14:06:11 +0900177 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700178 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800179 // The count of the connected legacy clients.
180 private int mLegacyClientCount = 0;
Paul Hub2e67d32023-04-18 05:50:14 +0000181 // The number of client that ever connected.
182 private int mClientNumberId = 1;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700183
Paul Hu23fa2022023-01-13 22:57:24 +0800184 private static class MdnsListener implements MdnsServiceBrowserListener {
185 protected final int mClientId;
186 protected final int mTransactionId;
187 @NonNull
188 protected final NsdServiceInfo mReqServiceInfo;
189 @NonNull
190 protected final String mListenedServiceType;
191
192 MdnsListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
193 @NonNull String listenedServiceType) {
194 mClientId = clientId;
195 mTransactionId = transactionId;
196 mReqServiceInfo = reqServiceInfo;
197 mListenedServiceType = listenedServiceType;
198 }
199
200 @NonNull
201 public String getListenedServiceType() {
202 return mListenedServiceType;
203 }
204
205 @Override
206 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) { }
207
208 @Override
209 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
210
211 @Override
212 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
213
214 @Override
215 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) { }
216
217 @Override
218 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
219
220 @Override
221 public void onSearchStoppedWithError(int error) { }
222
223 @Override
224 public void onSearchFailedToStart() { }
225
226 @Override
227 public void onDiscoveryQuerySent(@NonNull List<String> subtypes, int transactionId) { }
228
229 @Override
230 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
231 }
232
233 private class DiscoveryListener extends MdnsListener {
234
235 DiscoveryListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
236 @NonNull String listenServiceType) {
237 super(clientId, transactionId, reqServiceInfo, listenServiceType);
238 }
239
240 @Override
241 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu019621e2023-01-13 23:26:49 +0800242 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
243 NsdManager.SERVICE_FOUND,
244 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800245 }
246
247 @Override
248 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800249 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
250 NsdManager.SERVICE_LOST,
251 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800252 }
253 }
254
Paul Hu75069ed2023-01-14 00:31:09 +0800255 private class ResolutionListener extends MdnsListener {
256
257 ResolutionListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
258 @NonNull String listenServiceType) {
259 super(clientId, transactionId, reqServiceInfo, listenServiceType);
260 }
261
262 @Override
263 public void onServiceFound(MdnsServiceInfo serviceInfo) {
264 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
265 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
266 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
267 }
268 }
269
Paul Hu30bd70d2023-02-07 13:20:56 +0000270 private class ServiceInfoListener extends MdnsListener {
271
272 ServiceInfoListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
273 @NonNull String listenServiceType) {
274 super(clientId, transactionId, reqServiceInfo, listenServiceType);
275 }
276
277 @Override
278 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) {
279 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
280 NsdManager.SERVICE_UPDATED,
281 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
282 }
283
284 @Override
285 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) {
286 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
287 NsdManager.SERVICE_UPDATED,
288 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
289 }
290
291 @Override
292 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) {
293 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
294 NsdManager.SERVICE_UPDATED_LOST,
295 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
296 }
297 }
298
Paul Hu019621e2023-01-13 23:26:49 +0800299 /**
300 * Data class of mdns service callback information.
301 */
302 private static class MdnsEvent {
303 final int mClientId;
304 @NonNull
305 final String mRequestedServiceType;
306 @NonNull
307 final MdnsServiceInfo mMdnsServiceInfo;
308
309 MdnsEvent(int clientId, @NonNull String requestedServiceType,
310 @NonNull MdnsServiceInfo mdnsServiceInfo) {
311 mClientId = clientId;
312 mRequestedServiceType = requestedServiceType;
313 mMdnsServiceInfo = mdnsServiceInfo;
314 }
315 }
316
Irfan Sheriff75006652012-04-17 23:15:29 -0700317 private class NsdStateMachine extends StateMachine {
318
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700319 private final DefaultState mDefaultState = new DefaultState();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700320 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700321
322 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700323 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900324 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700325 }
326
Luke Huang92860f92021-06-23 06:29:30 +0000327 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800328 if (mIsDaemonStarted) {
329 if (DBG) Log.d(TAG, "Daemon is already started.");
330 return;
331 }
332 mMDnsManager.registerEventListener(mMDnsEventCallback);
333 mMDnsManager.startDaemon();
334 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000335 maybeScheduleStop();
Paul Hub2e67d32023-04-18 05:50:14 +0000336 mServiceLogs.log("Start mdns_responder daemon");
Luke Huang05298582021-06-13 16:52:05 +0000337 }
338
paulhu2b9ed952022-02-10 21:58:32 +0800339 private void maybeStopDaemon() {
340 if (!mIsDaemonStarted) {
341 if (DBG) Log.d(TAG, "Daemon has not been started.");
342 return;
343 }
344 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
345 mMDnsManager.stopDaemon();
346 mIsDaemonStarted = false;
Paul Hub2e67d32023-04-18 05:50:14 +0000347 mServiceLogs.log("Stop mdns_responder daemon");
paulhu2b9ed952022-02-10 21:58:32 +0800348 }
349
Luke Huang92860f92021-06-23 06:29:30 +0000350 private boolean isAnyRequestActive() {
351 return mIdToClientInfoMap.size() != 0;
352 }
353
354 private void scheduleStop() {
355 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
356 }
357 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800358 // The native daemon should stay alive and can't be cleanup
359 // if any legacy client connected.
360 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000361 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000362 }
363 }
364
Luke Huang92860f92021-06-23 06:29:30 +0000365 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000366 this.removeMessages(NsdManager.DAEMON_CLEANUP);
367 }
368
Paul Hu23fa2022023-01-13 22:57:24 +0800369 private void maybeStartMonitoringSockets() {
370 if (mIsMonitoringSocketsStarted) {
371 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
372 return;
373 }
374
375 mMdnsSocketProvider.startMonitoringSockets();
376 mIsMonitoringSocketsStarted = true;
377 }
378
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900379 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
380 if (!mIsMonitoringSocketsStarted) return;
381 if (isAnyRequestActive()) return;
382
Paul Hu58f20602023-02-18 11:41:07 +0800383 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800384 mIsMonitoringSocketsStarted = false;
385 }
386
Hugo Benichi803a2f02017-04-24 11:35:06 +0900387 NsdStateMachine(String name, Handler handler) {
388 super(name, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700389 addState(mDefaultState);
Irfan Sheriff75006652012-04-17 23:15:29 -0700390 addState(mEnabledState, mDefaultState);
paulhu5568f452021-11-30 13:31:29 +0800391 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900392 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700393 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700394 }
395
396 class DefaultState extends State {
397 @Override
398 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900399 final ClientInfo cInfo;
400 final int clientId = msg.arg2;
Irfan Sheriff75006652012-04-17 23:15:29 -0700401 switch (msg.what) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900402 case NsdManager.REGISTER_CLIENT:
Paul Hu2e0a88c2023-03-09 16:05:01 +0800403 final ConnectorArgs arg = (ConnectorArgs) msg.obj;
404 final INsdManagerCallback cb = arg.callback;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900405 try {
Paul Hu2e0a88c2023-03-09 16:05:01 +0800406 cb.asBinder().linkToDeath(arg.connector, 0);
Paul Hub2e67d32023-04-18 05:50:14 +0000407 final String tag = "Client" + arg.uid + "-" + mClientNumberId++;
408 cInfo = new ClientInfo(cb, arg.useJavaBackend,
409 mServiceLogs.forSubComponent(tag));
Paul Hu2e0a88c2023-03-09 16:05:01 +0800410 mClients.put(arg.connector, cInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900411 } catch (RemoteException e) {
412 Log.w(TAG, "Client " + clientId + " has already died");
Irfan Sheriff75006652012-04-17 23:15:29 -0700413 }
414 break;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900415 case NsdManager.UNREGISTER_CLIENT:
416 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
417 cInfo = mClients.remove(connector);
Dave Plattfeff2af2014-03-07 14:48:22 -0800418 if (cInfo != null) {
419 cInfo.expungeAllRequests();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900420 if (cInfo.isPreSClient()) {
Luke Huangf7277ed2021-07-12 21:15:10 +0800421 mLegacyClientCount -= 1;
422 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800423 }
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900424 maybeStopMonitoringSocketsIfNoActiveRequest();
Luke Huangf7277ed2021-07-12 21:15:10 +0800425 maybeScheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700426 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700427 case NsdManager.DISCOVER_SERVICES:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900428 cInfo = getClientInfoForReply(msg);
429 if (cInfo != null) {
430 cInfo.onDiscoverServicesFailed(
431 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
432 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700433 break;
434 case NsdManager.STOP_DISCOVERY:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900435 cInfo = getClientInfoForReply(msg);
436 if (cInfo != null) {
437 cInfo.onStopDiscoveryFailed(
438 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
439 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700440 break;
441 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900442 cInfo = getClientInfoForReply(msg);
443 if (cInfo != null) {
444 cInfo.onRegisterServiceFailed(
445 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
446 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700447 break;
448 case NsdManager.UNREGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900449 cInfo = getClientInfoForReply(msg);
450 if (cInfo != null) {
451 cInfo.onUnregisterServiceFailed(
452 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
453 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700454 break;
455 case NsdManager.RESOLVE_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900456 cInfo = getClientInfoForReply(msg);
457 if (cInfo != null) {
458 cInfo.onResolveServiceFailed(
459 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
460 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700461 break;
Paul Hub58deb72022-12-26 09:24:42 +0000462 case NsdManager.STOP_RESOLUTION:
463 cInfo = getClientInfoForReply(msg);
464 if (cInfo != null) {
465 cInfo.onStopResolutionFailed(
466 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
467 }
468 break;
Paul Hu18aeccc2022-12-27 08:48:48 +0000469 case NsdManager.REGISTER_SERVICE_CALLBACK:
470 cInfo = getClientInfoForReply(msg);
471 if (cInfo != null) {
472 cInfo.onServiceInfoCallbackRegistrationFailed(
473 clientId, NsdManager.FAILURE_BAD_PARAMETERS);
474 }
475 break;
Luke Huang05298582021-06-13 16:52:05 +0000476 case NsdManager.DAEMON_CLEANUP:
paulhu2b9ed952022-02-10 21:58:32 +0800477 maybeStopDaemon();
Luke Huang05298582021-06-13 16:52:05 +0000478 break;
Luke Huangf7277ed2021-07-12 21:15:10 +0800479 // This event should be only sent by the legacy (target SDK < S) clients.
480 // Mark the sending client as legacy.
481 case NsdManager.DAEMON_STARTUP:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900482 cInfo = getClientInfoForReply(msg);
Luke Huangf7277ed2021-07-12 21:15:10 +0800483 if (cInfo != null) {
484 cancelStop();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900485 cInfo.setPreSClient();
Luke Huangf7277ed2021-07-12 21:15:10 +0800486 mLegacyClientCount += 1;
487 maybeStartDaemon();
488 }
489 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700490 default:
paulhub2225702021-11-17 09:35:33 +0800491 Log.e(TAG, "Unhandled " + msg);
Irfan Sheriff75006652012-04-17 23:15:29 -0700492 return NOT_HANDLED;
493 }
494 return HANDLED;
495 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900496
497 private ClientInfo getClientInfoForReply(Message msg) {
498 final ListenerArgs args = (ListenerArgs) msg.obj;
499 return mClients.get(args.connector);
500 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700501 }
502
Irfan Sheriff75006652012-04-17 23:15:29 -0700503 class EnabledState extends State {
504 @Override
505 public void enter() {
506 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700507 }
508
509 @Override
510 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000511 // TODO: it is incorrect to stop the daemon without expunging all requests
512 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000513 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700514 }
515
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700516 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900517 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800518 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700519 return true;
520 }
521 return false;
522 }
523
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900524 private void storeLegacyRequestMap(int clientId, int globalId, ClientInfo clientInfo,
525 int what) {
526 clientInfo.mClientRequests.put(clientId, new LegacyClientRequest(globalId, what));
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700527 mIdToClientInfoMap.put(globalId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000528 // Remove the cleanup event because here comes a new request.
529 cancelStop();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700530 }
531
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900532 private void storeAdvertiserRequestMap(int clientId, int globalId,
Paul Hu23fa2022023-01-13 22:57:24 +0800533 ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900534 clientInfo.mClientRequests.put(clientId, new AdvertiserClientRequest(globalId));
535 mIdToClientInfoMap.put(globalId, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800536 }
537
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900538 private void removeRequestMap(int clientId, int globalId, ClientInfo clientInfo) {
539 final ClientRequest existing = clientInfo.mClientRequests.get(clientId);
540 if (existing == null) return;
541 clientInfo.mClientRequests.remove(clientId);
542 mIdToClientInfoMap.remove(globalId);
543
544 if (existing instanceof LegacyClientRequest) {
545 maybeScheduleStop();
546 } else {
547 maybeStopMonitoringSocketsIfNoActiveRequest();
548 }
549 }
550
551 private void storeDiscoveryManagerRequestMap(int clientId, int globalId,
552 MdnsListener listener, ClientInfo clientInfo) {
553 clientInfo.mClientRequests.put(clientId,
554 new DiscoveryManagerRequest(globalId, listener));
555 mIdToClientInfoMap.put(globalId, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800556 }
557
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900558 /**
559 * Truncate a service name to up to 63 UTF-8 bytes.
560 *
561 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
562 * names used in registerService follows historical behavior (see mdnsresponder
563 * handle_regservice_request).
564 */
565 @NonNull
566 private String truncateServiceName(@NonNull String originalName) {
Yuyang Huangde802c82023-05-02 17:14:22 +0900567 return MdnsUtils.truncateServiceName(originalName, MAX_LABEL_LENGTH);
Paul Hu23fa2022023-01-13 22:57:24 +0800568 }
569
Paul Hue4f5f252023-02-16 21:13:47 +0800570 private void stopDiscoveryManagerRequest(ClientRequest request, int clientId, int id,
571 ClientInfo clientInfo) {
572 clientInfo.unregisterMdnsListenerFromRequest(request);
573 removeRequestMap(clientId, id, clientInfo);
574 }
575
Irfan Sheriff75006652012-04-17 23:15:29 -0700576 @Override
577 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900578 final ClientInfo clientInfo;
579 final int id;
580 final int clientId = msg.arg2;
581 final ListenerArgs args;
Irfan Sheriff75006652012-04-17 23:15:29 -0700582 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800583 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800584 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900585 args = (ListenerArgs) msg.obj;
586 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000587 // If the binder death notification for a INsdManagerCallback was received
588 // before any calls are received by NsdService, the clientInfo would be
589 // cleared and cause NPE. Add a null check here to prevent this corner case.
590 if (clientInfo == null) {
591 Log.e(TAG, "Unknown connector in discovery");
592 break;
593 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700594
595 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900596 clientInfo.onDiscoverServicesFailed(
597 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriff75006652012-04-17 23:15:29 -0700598 break;
599 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700600
Paul Hu23fa2022023-01-13 22:57:24 +0800601 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700602 id = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900603 final String serviceType = constructServiceType(info.getServiceType());
Paul Hu2e0a88c2023-03-09 16:05:01 +0800604 if (clientInfo.mUseJavaBackend
605 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900606 || useDiscoveryManagerForType(serviceType)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800607 if (serviceType == null) {
608 clientInfo.onDiscoverServicesFailed(clientId,
609 NsdManager.FAILURE_INTERNAL_ERROR);
610 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700611 }
Paul Hu23fa2022023-01-13 22:57:24 +0800612
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900613 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800614 maybeStartMonitoringSockets();
615 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900616 new DiscoveryListener(clientId, id, info, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800617 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
618 .setNetwork(info.getNetwork())
619 .setIsPassiveMode(true)
620 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900621 mMdnsDiscoveryManager.registerListener(
622 listenServiceType, listener, options);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900623 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800624 clientInfo.onDiscoverServicesStarted(clientId, info);
Paul Hub2e67d32023-04-18 05:50:14 +0000625 clientInfo.log("Register a DiscoveryListener " + id
626 + " for service type:" + listenServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700627 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800628 maybeStartDaemon();
629 if (discoverServices(id, info)) {
630 if (DBG) {
631 Log.d(TAG, "Discover " + msg.arg2 + " " + id
632 + info.getServiceType());
633 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900634 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu23fa2022023-01-13 22:57:24 +0800635 clientInfo.onDiscoverServicesStarted(clientId, info);
636 } else {
637 stopServiceDiscovery(id);
638 clientInfo.onDiscoverServicesFailed(clientId,
639 NsdManager.FAILURE_INTERNAL_ERROR);
640 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700641 }
642 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800643 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900644 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800645 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900646 args = (ListenerArgs) msg.obj;
647 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000648 // If the binder death notification for a INsdManagerCallback was received
649 // before any calls are received by NsdService, the clientInfo would be
650 // cleared and cause NPE. Add a null check here to prevent this corner case.
651 if (clientInfo == null) {
652 Log.e(TAG, "Unknown connector in stop discovery");
653 break;
654 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700655
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900656 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
657 if (request == null) {
658 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700659 break;
660 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900661 id = request.mGlobalId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900662 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
663 // point, so this needs to check the type of the original request to
664 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900665 if (request instanceof DiscoveryManagerRequest) {
Paul Hue4f5f252023-02-16 21:13:47 +0800666 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900667 clientInfo.onStopDiscoverySucceeded(clientId);
Paul Hub2e67d32023-04-18 05:50:14 +0000668 clientInfo.log("Unregister the DiscoveryListener " + id);
Irfan Sheriff75006652012-04-17 23:15:29 -0700669 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800670 removeRequestMap(clientId, id, clientInfo);
671 if (stopServiceDiscovery(id)) {
672 clientInfo.onStopDiscoverySucceeded(clientId);
673 } else {
674 clientInfo.onStopDiscoveryFailed(
675 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
676 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700677 }
678 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900679 }
680 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800681 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900682 args = (ListenerArgs) msg.obj;
683 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000684 // If the binder death notification for a INsdManagerCallback was received
685 // before any calls are received by NsdService, the clientInfo would be
686 // cleared and cause NPE. Add a null check here to prevent this corner case.
687 if (clientInfo == null) {
688 Log.e(TAG, "Unknown connector in registration");
689 break;
690 }
691
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700692 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900693 clientInfo.onRegisterServiceFailed(
694 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700695 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700696 }
697
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700698 id = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900699 final NsdServiceInfo serviceInfo = args.serviceInfo;
700 final String serviceType = serviceInfo.getServiceType();
701 final String registerServiceType = constructServiceType(serviceType);
Paul Hu2e0a88c2023-03-09 16:05:01 +0800702 if (clientInfo.mUseJavaBackend
703 || mDeps.isMdnsAdvertiserEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900704 || useAdvertiserForType(registerServiceType)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900705 if (registerServiceType == null) {
706 Log.e(TAG, "Invalid service type: " + serviceType);
707 clientInfo.onRegisterServiceFailed(clientId,
708 NsdManager.FAILURE_INTERNAL_ERROR);
709 break;
710 }
711 serviceInfo.setServiceType(registerServiceType);
712 serviceInfo.setServiceName(truncateServiceName(
713 serviceInfo.getServiceName()));
714
715 maybeStartMonitoringSockets();
716 mAdvertiser.addService(id, serviceInfo);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900717 storeAdvertiserRequestMap(clientId, id, clientInfo);
Irfan Sheriff75006652012-04-17 23:15:29 -0700718 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900719 maybeStartDaemon();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900720 if (registerService(id, serviceInfo)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900721 if (DBG) Log.d(TAG, "Register " + clientId + " " + id);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900722 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900723 // Return success after mDns reports success
724 } else {
725 unregisterService(id);
726 clientInfo.onRegisterServiceFailed(
727 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
728 }
729
Irfan Sheriff75006652012-04-17 23:15:29 -0700730 }
731 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900732 }
733 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800734 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900735 args = (ListenerArgs) msg.obj;
736 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000737 // If the binder death notification for a INsdManagerCallback was received
738 // before any calls are received by NsdService, the clientInfo would be
739 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900740 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800741 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700742 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700743 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900744 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
745 if (request == null) {
746 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
747 break;
748 }
749 id = request.mGlobalId;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900750 removeRequestMap(clientId, id, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900751
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900752 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
753 // so this needs to check the type of the original request to unregister
754 // instead of looking at the flag value.
755 if (request instanceof AdvertiserClientRequest) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900756 mAdvertiser.removeService(id);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900757 clientInfo.onUnregisterServiceSucceeded(clientId);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700758 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900759 if (unregisterService(id)) {
760 clientInfo.onUnregisterServiceSucceeded(clientId);
761 } else {
762 clientInfo.onUnregisterServiceFailed(
763 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
764 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700765 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700766 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900767 }
Paul Hu75069ed2023-01-14 00:31:09 +0800768 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800769 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900770 args = (ListenerArgs) msg.obj;
771 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000772 // If the binder death notification for a INsdManagerCallback was received
773 // before any calls are received by NsdService, the clientInfo would be
774 // cleared and cause NPE. Add a null check here to prevent this corner case.
775 if (clientInfo == null) {
776 Log.e(TAG, "Unknown connector in resolution");
777 break;
778 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700779
Paul Hu75069ed2023-01-14 00:31:09 +0800780 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700781 id = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900782 final String serviceType = constructServiceType(info.getServiceType());
Paul Hu2e0a88c2023-03-09 16:05:01 +0800783 if (clientInfo.mUseJavaBackend
784 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900785 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800786 if (serviceType == null) {
787 clientInfo.onResolveServiceFailed(clientId,
788 NsdManager.FAILURE_INTERNAL_ERROR);
789 break;
790 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900791 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +0800792
793 maybeStartMonitoringSockets();
794 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900795 new ResolutionListener(clientId, id, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800796 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
797 .setNetwork(info.getNetwork())
798 .setIsPassiveMode(true)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900799 .setResolveInstanceName(info.getServiceName())
Paul Hu75069ed2023-01-14 00:31:09 +0800800 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900801 mMdnsDiscoveryManager.registerListener(
802 resolveServiceType, listener, options);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900803 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Paul Hub2e67d32023-04-18 05:50:14 +0000804 clientInfo.log("Register a ResolutionListener " + id
805 + " for service type:" + resolveServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700806 } else {
Paul Hu75069ed2023-01-14 00:31:09 +0800807 if (clientInfo.mResolvedService != null) {
808 clientInfo.onResolveServiceFailed(
809 clientId, NsdManager.FAILURE_ALREADY_ACTIVE);
810 break;
811 }
812
813 maybeStartDaemon();
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900814 if (resolveService(id, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800815 clientInfo.mResolvedService = new NsdServiceInfo();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900816 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu75069ed2023-01-14 00:31:09 +0800817 } else {
818 clientInfo.onResolveServiceFailed(
819 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
820 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700821 }
822 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800823 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900824 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +0000825 if (DBG) Log.d(TAG, "Stop service resolution");
826 args = (ListenerArgs) msg.obj;
827 clientInfo = mClients.get(args.connector);
828 // 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 stop resolution");
833 break;
834 }
835
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900836 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
837 if (request == null) {
838 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
839 break;
840 }
841 id = request.mGlobalId;
Paul Hue4f5f252023-02-16 21:13:47 +0800842 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
843 // point, so this needs to check the type of the original request to
844 // unregister instead of looking at the flag value.
845 if (request instanceof DiscoveryManagerRequest) {
846 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Paul Hub58deb72022-12-26 09:24:42 +0000847 clientInfo.onStopResolutionSucceeded(clientId);
Paul Hub2e67d32023-04-18 05:50:14 +0000848 clientInfo.log("Unregister the ResolutionListener " + id);
Paul Hub58deb72022-12-26 09:24:42 +0000849 } else {
Paul Hue4f5f252023-02-16 21:13:47 +0800850 removeRequestMap(clientId, id, clientInfo);
851 if (stopResolveService(id)) {
852 clientInfo.onStopResolutionSucceeded(clientId);
853 } else {
854 clientInfo.onStopResolutionFailed(
855 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
856 }
857 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +0000858 }
Paul Hub58deb72022-12-26 09:24:42 +0000859 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900860 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000861 case NsdManager.REGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +0000862 if (DBG) Log.d(TAG, "Register a service callback");
863 args = (ListenerArgs) msg.obj;
864 clientInfo = mClients.get(args.connector);
865 // If the binder death notification for a INsdManagerCallback was received
866 // before any calls are received by NsdService, the clientInfo would be
867 // cleared and cause NPE. Add a null check here to prevent this corner case.
868 if (clientInfo == null) {
869 Log.e(TAG, "Unknown connector in callback registration");
870 break;
871 }
872
Paul Hu30bd70d2023-02-07 13:20:56 +0000873 final NsdServiceInfo info = args.serviceInfo;
874 id = getUniqueId();
875 final String serviceType = constructServiceType(info.getServiceType());
876 if (serviceType == null) {
877 clientInfo.onServiceInfoCallbackRegistrationFailed(clientId,
878 NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +0000879 break;
880 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000881 final String resolveServiceType = serviceType + ".local";
Paul Hu18aeccc2022-12-27 08:48:48 +0000882
Paul Hu30bd70d2023-02-07 13:20:56 +0000883 maybeStartMonitoringSockets();
884 final MdnsListener listener =
885 new ServiceInfoListener(clientId, id, info, resolveServiceType);
886 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
887 .setNetwork(info.getNetwork())
888 .setIsPassiveMode(true)
889 .setResolveInstanceName(info.getServiceName())
890 .build();
891 mMdnsDiscoveryManager.registerListener(
892 resolveServiceType, listener, options);
893 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Paul Hub2e67d32023-04-18 05:50:14 +0000894 clientInfo.log("Register a ServiceInfoListener " + id
895 + " for service type:" + resolveServiceType);
Paul Hu18aeccc2022-12-27 08:48:48 +0000896 break;
Paul Hu30bd70d2023-02-07 13:20:56 +0000897 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900898 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +0000899 if (DBG) Log.d(TAG, "Unregister a service callback");
900 args = (ListenerArgs) msg.obj;
901 clientInfo = mClients.get(args.connector);
902 // If the binder death notification for a INsdManagerCallback was received
903 // before any calls are received by NsdService, the clientInfo would be
904 // cleared and cause NPE. Add a null check here to prevent this corner case.
905 if (clientInfo == null) {
906 Log.e(TAG, "Unknown connector in callback unregistration");
907 break;
908 }
909
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900910 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
911 if (request == null) {
Paul Hu30bd70d2023-02-07 13:20:56 +0000912 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE_CALLBACK");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900913 break;
914 }
915 id = request.mGlobalId;
Paul Hu30bd70d2023-02-07 13:20:56 +0000916 if (request instanceof DiscoveryManagerRequest) {
917 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Paul Hu18aeccc2022-12-27 08:48:48 +0000918 clientInfo.onServiceInfoCallbackUnregistered(clientId);
Paul Hub2e67d32023-04-18 05:50:14 +0000919 clientInfo.log("Unregister the ServiceInfoListener " + id);
Paul Hu18aeccc2022-12-27 08:48:48 +0000920 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +0000921 loge("Unregister failed with non-DiscoveryManagerRequest.");
Paul Hu18aeccc2022-12-27 08:48:48 +0000922 }
Paul Hu18aeccc2022-12-27 08:48:48 +0000923 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900924 }
paulhu2b9ed952022-02-10 21:58:32 +0800925 case MDNS_SERVICE_EVENT:
926 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +0900927 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700928 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700929 break;
Paul Hu019621e2023-01-13 23:26:49 +0800930 case MDNS_DISCOVERY_MANAGER_EVENT:
931 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
932 return NOT_HANDLED;
933 }
934 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700935 default:
Hugo Benichif0c84092017-04-05 14:43:29 +0900936 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700937 }
Hugo Benichif0c84092017-04-05 14:43:29 +0900938 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700939 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700940
paulhu2b9ed952022-02-10 21:58:32 +0800941 private boolean handleMDnsServiceEvent(int code, int id, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700942 NsdServiceInfo servInfo;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700943 ClientInfo clientInfo = mIdToClientInfoMap.get(id);
944 if (clientInfo == null) {
paulhu2b9ed952022-02-10 21:58:32 +0800945 Log.e(TAG, String.format("id %d for %d has no client mapping", id, code));
Hugo Benichif0c84092017-04-05 14:43:29 +0900946 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700947 }
948
949 /* This goes in response as msg.arg2 */
Christopher Lane74411222014-04-25 18:39:07 -0700950 int clientId = clientInfo.getClientId(id);
951 if (clientId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -0700952 // This can happen because of race conditions. For example,
953 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
954 // and we may get in this situation.
paulhu2b9ed952022-02-10 21:58:32 +0800955 Log.d(TAG, String.format("%d for listener id %d that is no longer active",
956 code, id));
Hugo Benichif0c84092017-04-05 14:43:29 +0900957 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700958 }
Hugo Benichi32be63d2017-04-05 14:06:11 +0900959 if (DBG) {
paulhu2b9ed952022-02-10 21:58:32 +0800960 Log.d(TAG, String.format("MDns service event code:%d id=%d", code, id));
Hugo Benichi32be63d2017-04-05 14:06:11 +0900961 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700962 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +0800963 case IMDnsEventListener.SERVICE_FOUND: {
964 final DiscoveryInfo info = (DiscoveryInfo) obj;
965 final String name = info.serviceName;
966 final String type = info.registrationType;
967 servInfo = new NsdServiceInfo(name, type);
968 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900969 if (foundNetId == 0L) {
970 // Ignore services that do not have a Network: they are not usable
971 // by apps, as they would need privileged permissions to use
972 // interfaces that do not have an associated Network.
973 break;
974 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +0900975 if (foundNetId == INetd.DUMMY_NET_ID) {
976 // Ignore services on the dummy0 interface: they are only seen when
977 // discovering locally advertised services, and are not reachable
978 // through that interface.
979 break;
980 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900981 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900982 clientInfo.onServiceFound(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700983 break;
paulhu2b9ed952022-02-10 21:58:32 +0800984 }
985 case IMDnsEventListener.SERVICE_LOST: {
986 final DiscoveryInfo info = (DiscoveryInfo) obj;
987 final String name = info.serviceName;
988 final String type = info.registrationType;
989 final int lostNetId = info.netId;
990 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900991 // The network could be set to null (netId 0) if it was torn down when the
992 // service is lost
993 // TODO: avoid returning null in that case, possibly by remembering
994 // found services on the same interface index and their network at the time
995 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900996 clientInfo.onServiceLost(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700997 break;
paulhu2b9ed952022-02-10 21:58:32 +0800998 }
999 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001000 clientInfo.onDiscoverServicesFailed(
1001 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001002 break;
paulhu2b9ed952022-02-10 21:58:32 +08001003 case IMDnsEventListener.SERVICE_REGISTERED: {
1004 final RegistrationInfo info = (RegistrationInfo) obj;
1005 final String name = info.serviceName;
1006 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001007 clientInfo.onRegisterServiceSucceeded(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001008 break;
paulhu2b9ed952022-02-10 21:58:32 +08001009 }
1010 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001011 clientInfo.onRegisterServiceFailed(
1012 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001013 break;
paulhu2b9ed952022-02-10 21:58:32 +08001014 case IMDnsEventListener.SERVICE_RESOLVED: {
1015 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001016 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +08001017 final String fullName = info.serviceFullName;
1018 while (index < fullName.length() && fullName.charAt(index) != '.') {
1019 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001020 ++index;
1021 }
1022 ++index;
1023 }
paulhu2b9ed952022-02-10 21:58:32 +08001024 if (index >= fullName.length()) {
1025 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001026 break;
1027 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001028
paulhube186602022-04-12 07:18:23 +00001029 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001030 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001031 String type = rest.replace(".local.", "");
1032
Paul Hu30bd70d2023-02-07 13:20:56 +00001033 final NsdServiceInfo serviceInfo = clientInfo.mResolvedService;
Paul Hu18aeccc2022-12-27 08:48:48 +00001034 serviceInfo.setServiceName(name);
1035 serviceInfo.setServiceType(type);
1036 serviceInfo.setPort(info.port);
1037 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001038 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001039
1040 stopResolveService(id);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001041 removeRequestMap(clientId, id, clientInfo);
1042
paulhu2b9ed952022-02-10 21:58:32 +08001043 final int id2 = getUniqueId();
1044 if (getAddrInfo(id2, info.hostname, info.interfaceIdx)) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001045 storeLegacyRequestMap(clientId, id2, clientInfo,
1046 NsdManager.RESOLVE_SERVICE);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001047 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001048 clientInfo.onResolveServiceFailed(
1049 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1050 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001051 }
1052 break;
paulhu2b9ed952022-02-10 21:58:32 +08001053 }
1054 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001055 /* NNN resolveId errorCode */
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001056 stopResolveService(id);
1057 removeRequestMap(clientId, id, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001058 clientInfo.onResolveServiceFailed(
1059 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1060 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001061 break;
paulhu2b9ed952022-02-10 21:58:32 +08001062 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001063 /* NNN resolveId errorCode */
1064 stopGetAddrInfo(id);
1065 removeRequestMap(clientId, id, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001066 clientInfo.onResolveServiceFailed(
1067 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1068 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001069 break;
paulhu2b9ed952022-02-10 21:58:32 +08001070 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001071 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001072 final GetAddressInfo info = (GetAddressInfo) obj;
1073 final String address = info.address;
1074 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001075 InetAddress serviceHost = null;
1076 try {
paulhu2b9ed952022-02-10 21:58:32 +08001077 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001078 } catch (UnknownHostException e) {
1079 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1080 }
1081
1082 // If the resolved service is on an interface without a network, consider it
1083 // as a failure: it would not be usable by apps as they would need
1084 // privileged permissions.
Paul Hu30bd70d2023-02-07 13:20:56 +00001085 if (netId != NETID_UNSET && serviceHost != null) {
1086 clientInfo.mResolvedService.setHost(serviceHost);
1087 setServiceNetworkForCallback(clientInfo.mResolvedService,
1088 netId, info.interfaceIdx);
1089 clientInfo.onResolveServiceSucceeded(
1090 clientId, clientInfo.mResolvedService);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001091 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001092 clientInfo.onResolveServiceFailed(
1093 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001094 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001095 stopGetAddrInfo(id);
1096 removeRequestMap(clientId, id, clientInfo);
1097 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001098 break;
paulhu2b9ed952022-02-10 21:58:32 +08001099 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001100 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001101 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001102 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001103 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001104 }
Paul Hu019621e2023-01-13 23:26:49 +08001105
1106 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(final MdnsEvent event) {
1107 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1108 final String serviceType = event.mRequestedServiceType;
1109 final String serviceName = serviceInfo.getServiceInstanceName();
1110 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1111 final Network network = serviceInfo.getNetwork();
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001112 // In MdnsDiscoveryManagerEvent, the Network can be null which means it is a
1113 // network for Tethering interface. In other words, the network == null means the
1114 // network has netId = INetd.LOCAL_NET_ID.
Paul Hu019621e2023-01-13 23:26:49 +08001115 setServiceNetworkForCallback(
1116 servInfo,
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001117 network == null ? INetd.LOCAL_NET_ID : network.netId,
Paul Hu019621e2023-01-13 23:26:49 +08001118 serviceInfo.getInterfaceIndex());
1119 return servInfo;
1120 }
1121
1122 private boolean handleMdnsDiscoveryManagerEvent(
1123 int transactionId, int code, Object obj) {
1124 final ClientInfo clientInfo = mIdToClientInfoMap.get(transactionId);
1125 if (clientInfo == null) {
1126 Log.e(TAG, String.format(
1127 "id %d for %d has no client mapping", transactionId, code));
1128 return false;
1129 }
1130
1131 final MdnsEvent event = (MdnsEvent) obj;
1132 final int clientId = event.mClientId;
Paul Hu319751a2023-01-13 23:56:34 +08001133 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event);
Paul Hu019621e2023-01-13 23:26:49 +08001134 if (DBG) {
1135 Log.d(TAG, String.format("MdnsDiscoveryManager event code=%s transactionId=%d",
1136 NsdManager.nameOf(code), transactionId));
1137 }
1138 switch (code) {
1139 case NsdManager.SERVICE_FOUND:
Paul Hu319751a2023-01-13 23:56:34 +08001140 clientInfo.onServiceFound(clientId, info);
1141 break;
1142 case NsdManager.SERVICE_LOST:
1143 clientInfo.onServiceLost(clientId, info);
Paul Hu019621e2023-01-13 23:26:49 +08001144 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001145 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001146 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
1147 if (request == null) {
1148 Log.e(TAG, "Unknown client request in RESOLVE_SERVICE_SUCCEEDED");
1149 break;
1150 }
Paul Hu75069ed2023-01-14 00:31:09 +08001151 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1152 // Add '.' in front of the service type that aligns with historical behavior
1153 info.setServiceType("." + event.mRequestedServiceType);
1154 info.setPort(serviceInfo.getPort());
1155
1156 Map<String, String> attrs = serviceInfo.getAttributes();
1157 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1158 final String key = kv.getKey();
1159 try {
1160 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1161 } catch (IllegalArgumentException e) {
1162 Log.e(TAG, "Invalid attribute", e);
1163 }
1164 }
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001165 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu2b865912023-03-06 14:27:53 +08001166 if (addresses.size() != 0) {
1167 info.setHostAddresses(addresses);
Paul Hu75069ed2023-01-14 00:31:09 +08001168 clientInfo.onResolveServiceSucceeded(clientId, info);
Paul Hu2b865912023-03-06 14:27:53 +08001169 } else {
1170 // No address. Notify resolution failure.
Paul Hu75069ed2023-01-14 00:31:09 +08001171 clientInfo.onResolveServiceFailed(
1172 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1173 }
1174
1175 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001176 if (!(request instanceof DiscoveryManagerRequest)) {
1177 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1178 break;
1179 }
Paul Hue4f5f252023-02-16 21:13:47 +08001180 stopDiscoveryManagerRequest(request, clientId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001181 break;
1182 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001183 case NsdManager.SERVICE_UPDATED: {
1184 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1185 info.setPort(serviceInfo.getPort());
1186
1187 Map<String, String> attrs = serviceInfo.getAttributes();
1188 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1189 final String key = kv.getKey();
1190 try {
1191 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1192 } catch (IllegalArgumentException e) {
1193 Log.e(TAG, "Invalid attribute", e);
1194 }
1195 }
1196
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001197 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001198 info.setHostAddresses(addresses);
1199 clientInfo.onServiceUpdated(clientId, info);
1200 break;
1201 }
1202 case NsdManager.SERVICE_UPDATED_LOST:
1203 clientInfo.onServiceUpdatedLost(clientId);
1204 break;
Paul Hu019621e2023-01-13 23:26:49 +08001205 default:
1206 return false;
1207 }
1208 return true;
1209 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001210 }
1211 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001212
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001213 @NonNull
1214 private static List<InetAddress> getInetAddresses(@NonNull MdnsServiceInfo serviceInfo) {
1215 final List<String> v4Addrs = serviceInfo.getIpv4Addresses();
1216 final List<String> v6Addrs = serviceInfo.getIpv6Addresses();
1217 final List<InetAddress> addresses = new ArrayList<>(v4Addrs.size() + v6Addrs.size());
1218 for (String ipv4Address : v4Addrs) {
1219 try {
1220 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1221 } catch (IllegalArgumentException e) {
1222 Log.wtf(TAG, "Invalid ipv4 address", e);
1223 }
1224 }
1225 for (String ipv6Address : v6Addrs) {
1226 try {
Yuyang Huanga6a6ff92023-04-24 13:33:34 +09001227 final Inet6Address addr = (Inet6Address) InetAddresses.parseNumericAddress(
1228 ipv6Address);
1229 addresses.add(InetAddressUtils.withScopeId(addr, serviceInfo.getInterfaceIndex()));
1230 } catch (IllegalArgumentException e) {
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001231 Log.wtf(TAG, "Invalid ipv6 address", e);
1232 }
1233 }
1234 return addresses;
1235 }
1236
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001237 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1238 switch (netId) {
1239 case NETID_UNSET:
1240 info.setNetwork(null);
1241 break;
1242 case INetd.LOCAL_NET_ID:
1243 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1244 // visible / usable for apps, so do not return it. Store the interface
1245 // index instead, so at least if the client tries to resolve the service
1246 // with that NsdServiceInfo, it will be done on the same interface.
1247 // If they recreate the NsdServiceInfo themselves, resolution would be
1248 // done on all interfaces as before T, which should also work.
1249 info.setNetwork(null);
1250 info.setInterfaceIndex(ifaceIdx);
1251 break;
1252 default:
1253 info.setNetwork(new Network(netId));
1254 }
1255 }
1256
paulhube186602022-04-12 07:18:23 +00001257 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1258 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1259 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1260 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1261 private String unescape(String s) {
1262 StringBuilder sb = new StringBuilder(s.length());
1263 for (int i = 0; i < s.length(); ++i) {
1264 char c = s.charAt(i);
1265 if (c == '\\') {
1266 if (++i >= s.length()) {
1267 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1268 break;
1269 }
1270 c = s.charAt(i);
1271 if (c != '.' && c != '\\') {
1272 if (i + 2 >= s.length()) {
1273 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1274 break;
1275 }
1276 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1277 + (s.charAt(i + 2) - '0'));
1278 i += 2;
1279 }
1280 }
1281 sb.append(c);
1282 }
1283 return sb.toString();
1284 }
1285
Paul Hu7445e3d2023-03-03 15:14:00 +08001286 /**
1287 * Check the given service type is valid and construct it to a service type
1288 * which can use for discovery / resolution service.
1289 *
1290 * <p> The valid service type should be 2 labels, or 3 labels if the query is for a
1291 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1292 * underscore; they are alphanumerical characters or dashes or underscore, except the
1293 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1294 *
1295 * @param serviceType the request service type for discovery / resolution service
1296 * @return constructed service type or null if the given service type is invalid.
1297 */
1298 @Nullable
1299 public static String constructServiceType(String serviceType) {
1300 if (TextUtils.isEmpty(serviceType)) return null;
1301
1302 final Pattern serviceTypePattern = Pattern.compile(
1303 "^(_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]\\.)?"
1304 + "(_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]\\._(?:tcp|udp))"
1305 // Drop '.' at the end of service type that is compatible with old backend.
1306 + "\\.?$");
1307 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1308 if (!matcher.matches()) return null;
1309 return matcher.group(1) == null
1310 ? matcher.group(2)
1311 : matcher.group(1) + "_sub." + matcher.group(2);
1312 }
1313
Hugo Benichi803a2f02017-04-24 11:35:06 +09001314 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001315 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001316 this(ctx, handler, cleanupDelayMs, new Dependencies());
1317 }
1318
1319 @VisibleForTesting
1320 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001321 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001322 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001323 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001324 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001325 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1326 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001327 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001328
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001329 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper());
Yuyang Huang700778b2023-03-08 16:17:05 +09001330 // Netlink monitor starts on boot, and intentionally never stopped, to ensure that all
1331 // address events are received.
1332 handler.post(mMdnsSocketProvider::startNetLinkMonitor);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001333 mMdnsSocketClient =
1334 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider);
1335 mMdnsDiscoveryManager =
1336 deps.makeMdnsDiscoveryManager(new ExecutorProvider(), mMdnsSocketClient);
1337 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1338 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
1339 new AdvertiserCallback());
Paul Hu4bd98ef2023-01-12 13:42:07 +08001340 }
1341
1342 /**
1343 * Dependencies of NsdService, for injection in tests.
1344 */
1345 @VisibleForTesting
1346 public static class Dependencies {
1347 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001348 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001349 *
1350 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001351 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001352 */
1353 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi278db582023-04-21 12:35:22 +09001354 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1355 MDNS_DISCOVERY_MANAGER_VERSION, DeviceConfigUtils.TETHERING_MODULE_NAME,
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +09001356 false /* defaultEnabled */);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001357 }
1358
1359 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001360 * Check whether the MdnsAdvertiser feature is enabled.
1361 *
1362 * @param context The global context information about an app environment.
1363 * @return true if the MdnsAdvertiser feature is enabled.
1364 */
1365 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi278db582023-04-21 12:35:22 +09001366 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1367 MDNS_ADVERTISER_VERSION, DeviceConfigUtils.TETHERING_MODULE_NAME,
1368 false /* defaultEnabled */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001369 }
1370
1371 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001372 * Get the type allowlist flag value.
1373 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1374 */
1375 @Nullable
1376 public String getTypeAllowlistFlags() {
1377 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1378 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1379 }
1380
1381 /**
1382 * @see DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)
1383 */
1384 public boolean isFeatureEnabled(Context context, String feature) {
1385 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1386 feature, DeviceConfigUtils.TETHERING_MODULE_NAME, false /* defaultEnabled */);
1387 }
1388
1389 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001390 * @see MdnsDiscoveryManager
1391 */
1392 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
1393 ExecutorProvider executorProvider, MdnsSocketClientBase socketClient) {
1394 return new MdnsDiscoveryManager(executorProvider, socketClient);
1395 }
1396
1397 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001398 * @see MdnsAdvertiser
1399 */
1400 public MdnsAdvertiser makeMdnsAdvertiser(
1401 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
1402 @NonNull MdnsAdvertiser.AdvertiserCallback cb) {
1403 return new MdnsAdvertiser(looper, socketProvider, cb);
1404 }
1405
1406 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001407 * @see MdnsSocketProvider
1408 */
1409 public MdnsSocketProvider makeMdnsSocketProvider(Context context, Looper looper) {
1410 return new MdnsSocketProvider(context, looper);
1411 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001412 }
1413
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001414 /**
1415 * Return whether a type is allowlisted to use the Java backend.
1416 * @param type The service type
1417 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1418 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1419 */
1420 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1421 @NonNull String flagPrefix) {
1422 if (type == null) return false;
1423 final String typesConfig = mDeps.getTypeAllowlistFlags();
1424 if (TextUtils.isEmpty(typesConfig)) return false;
1425
1426 final String mappingPrefix = type + ":";
1427 String mappedFlag = null;
1428 for (String mapping : TextUtils.split(typesConfig, ",")) {
1429 if (mapping.startsWith(mappingPrefix)) {
1430 mappedFlag = mapping.substring(mappingPrefix.length());
1431 break;
1432 }
1433 }
1434
1435 if (mappedFlag == null) return false;
1436
1437 return mDeps.isFeatureEnabled(mContext,
1438 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1439 }
1440
1441 private boolean useDiscoveryManagerForType(@Nullable String type) {
1442 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1443 }
1444
1445 private boolean useAdvertiserForType(@Nullable String type) {
1446 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1447 }
1448
paulhu1b35e822022-04-08 14:48:41 +08001449 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001450 HandlerThread thread = new HandlerThread(TAG);
1451 thread.start();
1452 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001453 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001454 return service;
1455 }
1456
paulhu2b9ed952022-02-10 21:58:32 +08001457 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1458 private final StateMachine mStateMachine;
1459
1460 MDnsEventCallback(StateMachine sm) {
1461 mStateMachine = sm;
1462 }
1463
1464 @Override
1465 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1466 mStateMachine.sendMessage(
1467 MDNS_SERVICE_EVENT, status.result, status.id, status);
1468 }
1469
1470 @Override
1471 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1472 mStateMachine.sendMessage(
1473 MDNS_SERVICE_EVENT, status.result, status.id, status);
1474 }
1475
1476 @Override
1477 public void onServiceResolutionStatus(final ResolutionInfo status) {
1478 mStateMachine.sendMessage(
1479 MDNS_SERVICE_EVENT, status.result, status.id, status);
1480 }
1481
1482 @Override
1483 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1484 mStateMachine.sendMessage(
1485 MDNS_SERVICE_EVENT, status.result, status.id, status);
1486 }
1487
1488 @Override
1489 public int getInterfaceVersion() throws RemoteException {
1490 return this.VERSION;
1491 }
1492
1493 @Override
1494 public String getInterfaceHash() throws RemoteException {
1495 return this.HASH;
1496 }
1497 }
1498
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001499 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
1500 @Override
1501 public void onRegisterServiceSucceeded(int serviceId, NsdServiceInfo registeredInfo) {
1502 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1503 if (clientInfo == null) return;
1504
1505 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1506 if (clientId < 0) return;
1507
1508 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1509 // historical behavior.
1510 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
1511 clientInfo.onRegisterServiceSucceeded(clientId, cbInfo);
1512 }
1513
1514 @Override
1515 public void onRegisterServiceFailed(int serviceId, int errorCode) {
1516 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1517 if (clientInfo == null) return;
1518
1519 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1520 if (clientId < 0) return;
1521
1522 clientInfo.onRegisterServiceFailed(clientId, errorCode);
1523 }
1524
1525 private ClientInfo getClientInfoOrLog(int serviceId) {
1526 final ClientInfo clientInfo = mIdToClientInfoMap.get(serviceId);
1527 if (clientInfo == null) {
1528 Log.e(TAG, String.format("Callback for service %d has no client", serviceId));
1529 }
1530 return clientInfo;
1531 }
1532
1533 private int getClientIdOrLog(@NonNull ClientInfo info, int serviceId) {
1534 final int clientId = info.getClientId(serviceId);
1535 if (clientId < 0) {
1536 Log.e(TAG, String.format("Client ID not found for service %d", serviceId));
1537 }
1538 return clientId;
1539 }
1540 }
1541
Paul Hu2e0a88c2023-03-09 16:05:01 +08001542 private static class ConnectorArgs {
1543 @NonNull public final NsdServiceConnector connector;
1544 @NonNull public final INsdManagerCallback callback;
1545 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001546 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001547
1548 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00001549 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08001550 this.connector = connector;
1551 this.callback = callback;
1552 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001553 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001554 }
1555 }
1556
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001557 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08001558 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001559 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu2e0a88c2023-03-09 16:05:01 +08001560 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001561 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00001562 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
1563 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend,
1564 Binder.getCallingUid())));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001565 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07001566 }
1567
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001568 private static class ListenerArgs {
1569 public final NsdServiceConnector connector;
1570 public final NsdServiceInfo serviceInfo;
1571 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
1572 this.connector = connector;
1573 this.serviceInfo = serviceInfo;
1574 }
1575 }
1576
1577 private class NsdServiceConnector extends INsdServiceConnector.Stub
1578 implements IBinder.DeathRecipient {
1579 @Override
1580 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
1581 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1582 NsdManager.REGISTER_SERVICE, 0, listenerKey,
1583 new ListenerArgs(this, serviceInfo)));
1584 }
1585
1586 @Override
1587 public void unregisterService(int listenerKey) {
1588 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1589 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
1590 new ListenerArgs(this, null)));
1591 }
1592
1593 @Override
1594 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
1595 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1596 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
1597 new ListenerArgs(this, serviceInfo)));
1598 }
1599
1600 @Override
1601 public void stopDiscovery(int listenerKey) {
1602 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1603 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
1604 }
1605
1606 @Override
1607 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
1608 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1609 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
1610 new ListenerArgs(this, serviceInfo)));
1611 }
1612
1613 @Override
Paul Hub58deb72022-12-26 09:24:42 +00001614 public void stopResolution(int listenerKey) {
1615 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1616 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
1617 }
1618
1619 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00001620 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
1621 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1622 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
1623 new ListenerArgs(this, serviceInfo)));
1624 }
1625
1626 @Override
1627 public void unregisterServiceInfoCallback(int listenerKey) {
1628 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1629 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
1630 new ListenerArgs(this, null)));
1631 }
1632
1633 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001634 public void startDaemon() {
1635 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1636 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
1637 }
1638
1639 @Override
1640 public void binderDied() {
1641 mNsdStateMachine.sendMessage(
1642 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
1643 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001644 }
1645
Hugo Benichi912db992017-04-24 16:41:03 +09001646 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07001647 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07001648 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09001649 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
1650 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07001651 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07001652 }
1653
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001654 private int getUniqueId() {
1655 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
1656 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001657 }
1658
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001659 private boolean registerService(int regId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09001660 if (DBG) {
paulhub2225702021-11-17 09:35:33 +08001661 Log.d(TAG, "registerService: " + regId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001662 }
Hugo Benichi6d706442017-04-24 16:19:58 +09001663 String name = service.getServiceName();
1664 String type = service.getServiceType();
1665 int port = service.getPort();
1666 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001667 final int registerInterface = getNetworkInterfaceIndex(service);
1668 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08001669 Log.e(TAG, "Interface to register service on not found");
1670 return false;
1671 }
1672 return mMDnsManager.registerService(regId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001673 }
1674
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001675 private boolean unregisterService(int regId) {
paulhu2b9ed952022-02-10 21:58:32 +08001676 return mMDnsManager.stopOperation(regId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001677 }
1678
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001679 private boolean discoverServices(int discoveryId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08001680 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001681 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
1682 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001683 Log.e(TAG, "Interface to discover service on not found");
1684 return false;
1685 }
paulhu2b9ed952022-02-10 21:58:32 +08001686 return mMDnsManager.discover(discoveryId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001687 }
1688
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001689 private boolean stopServiceDiscovery(int discoveryId) {
paulhu2b9ed952022-02-10 21:58:32 +08001690 return mMDnsManager.stopOperation(discoveryId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001691 }
1692
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001693 private boolean resolveService(int resolveId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001694 final String name = service.getServiceName();
1695 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001696 final int resolveInterface = getNetworkInterfaceIndex(service);
1697 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001698 Log.e(TAG, "Interface to resolve service on not found");
1699 return false;
1700 }
paulhu2b9ed952022-02-10 21:58:32 +08001701 return mMDnsManager.resolve(resolveId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001702 }
1703
1704 /**
1705 * Guess the interface to use to resolve or discover a service on a specific network.
1706 *
1707 * This is an imperfect guess, as for example the network may be gone or not yet fully
1708 * registered. This is fine as failing is correct if the network is gone, and a client
1709 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
1710 * this is to support the legacy mdnsresponder implementation, which historically resolved
1711 * services on an unspecified network.
1712 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001713 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
1714 final Network network = serviceInfo.getNetwork();
1715 if (network == null) {
1716 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
1717 // provided by NsdService from discovery results, and the service was found on an
1718 // interface that has no app-usable Network).
1719 if (serviceInfo.getInterfaceIndex() != 0) {
1720 return serviceInfo.getInterfaceIndex();
1721 }
1722 return IFACE_IDX_ANY;
1723 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001724
1725 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
1726 if (cm == null) {
1727 Log.wtf(TAG, "No ConnectivityManager for resolveService");
1728 return IFACE_IDX_ANY;
1729 }
1730 final LinkProperties lp = cm.getLinkProperties(network);
1731 if (lp == null) return IFACE_IDX_ANY;
1732
1733 // Only resolve on non-stacked interfaces
1734 final NetworkInterface iface;
1735 try {
1736 iface = NetworkInterface.getByName(lp.getInterfaceName());
1737 } catch (SocketException e) {
1738 Log.e(TAG, "Error querying interface", e);
1739 return IFACE_IDX_ANY;
1740 }
1741
1742 if (iface == null) {
1743 Log.e(TAG, "Interface not found: " + lp.getInterfaceName());
1744 return IFACE_IDX_ANY;
1745 }
1746
1747 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001748 }
1749
1750 private boolean stopResolveService(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001751 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001752 }
1753
paulhu2b9ed952022-02-10 21:58:32 +08001754 private boolean getAddrInfo(int resolveId, String hostname, int interfaceIdx) {
1755 return mMDnsManager.getServiceAddress(resolveId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001756 }
1757
1758 private boolean stopGetAddrInfo(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001759 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001760 }
1761
1762 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00001763 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1764 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001765
Paul Hub2e67d32023-04-18 05:50:14 +00001766 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
1767 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07001768 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00001769
1770 // Dump service and clients logs
1771 pw.println();
1772 pw.increaseIndent();
1773 mServiceLogs.reverseDump(pw);
1774 pw.decreaseIndent();
1775
1776 // Dump advertiser related logs
1777 pw.println();
1778 pw.println("Advertiser:");
1779 pw.increaseIndent();
1780 mAdvertiser.dump(pw);
1781 pw.decreaseIndent();
1782
1783 // Dump discoverymanager related logs
1784 pw.println();
1785 pw.println("DiscoveryManager:");
1786 pw.increaseIndent();
1787 mMdnsDiscoveryManager.dump(pw);
1788 pw.decreaseIndent();
1789
1790 // Dump socketprovider related logs
1791 pw.println();
1792 pw.println("SocketProvider:");
1793 pw.increaseIndent();
1794 mMdnsSocketProvider.dump(pw);
1795 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001796 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001797
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001798 private abstract static class ClientRequest {
1799 private final int mGlobalId;
1800
1801 private ClientRequest(int globalId) {
1802 mGlobalId = globalId;
1803 }
1804 }
1805
1806 private static class LegacyClientRequest extends ClientRequest {
1807 private final int mRequestCode;
1808
1809 private LegacyClientRequest(int globalId, int requestCode) {
1810 super(globalId);
1811 mRequestCode = requestCode;
1812 }
1813 }
1814
1815 private static class AdvertiserClientRequest extends ClientRequest {
1816 private AdvertiserClientRequest(int globalId) {
1817 super(globalId);
1818 }
1819 }
1820
1821 private static class DiscoveryManagerRequest extends ClientRequest {
1822 @NonNull
1823 private final MdnsListener mListener;
1824
1825 private DiscoveryManagerRequest(int globalId, @NonNull MdnsListener listener) {
1826 super(globalId);
1827 mListener = listener;
1828 }
1829 }
1830
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001831 /* Information tracked per client */
1832 private class ClientInfo {
1833
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001834 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001835 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001836 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001837 private NsdServiceInfo mResolvedService;
1838
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001839 /* A map from client-side ID (listenerKey) to the request */
1840 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08001841
Luke Huangf7277ed2021-07-12 21:15:10 +08001842 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001843 private boolean mIsPreSClient = false;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001844 // The flag of using java backend if the client's target SDK >= U
1845 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001846 // Store client logs
1847 private final SharedLog mClientLogs;
Luke Huangf7277ed2021-07-12 21:15:10 +08001848
Paul Hub2e67d32023-04-18 05:50:14 +00001849 private ClientInfo(INsdManagerCallback cb, boolean useJavaBackend, SharedLog sharedLog) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001850 mCb = cb;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001851 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001852 mClientLogs = sharedLog;
1853 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001854 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001855
1856 @Override
1857 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06001858 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07001859 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001860 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
1861 for (int i = 0; i < mClientRequests.size(); i++) {
1862 int clientID = mClientRequests.keyAt(i);
1863 sb.append("clientId ")
1864 .append(clientID)
1865 .append(" mDnsId ").append(mClientRequests.valueAt(i).mGlobalId)
1866 .append(" type ").append(
1867 mClientRequests.valueAt(i).getClass().getSimpleName())
1868 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07001869 }
1870 return sb.toString();
1871 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001872
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001873 private boolean isPreSClient() {
1874 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08001875 }
1876
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001877 private void setPreSClient() {
1878 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08001879 }
1880
Paul Hue4f5f252023-02-16 21:13:47 +08001881 private void unregisterMdnsListenerFromRequest(ClientRequest request) {
1882 final MdnsListener listener =
1883 ((DiscoveryManagerRequest) request).mListener;
1884 mMdnsDiscoveryManager.unregisterListener(
1885 listener.getListenedServiceType(), listener);
1886 }
1887
Dave Plattfeff2af2014-03-07 14:48:22 -08001888 // Remove any pending requests from the global map when we get rid of a client,
1889 // and send cancellations to the daemon.
1890 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00001891 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09001892 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001893 for (int i = 0; i < mClientRequests.size(); i++) {
1894 final int clientId = mClientRequests.keyAt(i);
1895 final ClientRequest request = mClientRequests.valueAt(i);
1896 final int globalId = request.mGlobalId;
Dave Plattfeff2af2014-03-07 14:48:22 -08001897 mIdToClientInfoMap.remove(globalId);
paulhub2225702021-11-17 09:35:33 +08001898 if (DBG) {
1899 Log.d(TAG, "Terminating client-ID " + clientId
1900 + " global-ID " + globalId + " type " + mClientRequests.get(clientId));
1901 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001902
1903 if (request instanceof DiscoveryManagerRequest) {
Paul Hue4f5f252023-02-16 21:13:47 +08001904 unregisterMdnsListenerFromRequest(request);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001905 continue;
1906 }
1907
1908 if (request instanceof AdvertiserClientRequest) {
1909 mAdvertiser.removeService(globalId);
1910 continue;
1911 }
1912
1913 if (!(request instanceof LegacyClientRequest)) {
1914 throw new IllegalStateException("Unknown request type: " + request.getClass());
1915 }
1916
1917 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08001918 case NsdManager.DISCOVER_SERVICES:
1919 stopServiceDiscovery(globalId);
1920 break;
1921 case NsdManager.RESOLVE_SERVICE:
1922 stopResolveService(globalId);
1923 break;
1924 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001925 unregisterService(globalId);
Dave Plattfeff2af2014-03-07 14:48:22 -08001926 break;
1927 default:
1928 break;
1929 }
1930 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001931 mClientRequests.clear();
1932 }
1933
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001934 // mClientRequests is a sparse array of listener id -> ClientRequest. For a given
1935 // mDnsClient id, return the corresponding listener id. mDnsClient id is also called a
1936 // global id.
Christopher Lane74411222014-04-25 18:39:07 -07001937 private int getClientId(final int globalId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001938 for (int i = 0; i < mClientRequests.size(); i++) {
1939 if (mClientRequests.valueAt(i).mGlobalId == globalId) {
1940 return mClientRequests.keyAt(i);
1941 }
Christopher Lane74411222014-04-25 18:39:07 -07001942 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001943 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07001944 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001945
Paul Hub2e67d32023-04-18 05:50:14 +00001946 private void log(String message) {
1947 mClientLogs.log(message);
1948 }
1949
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001950 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info) {
1951 try {
1952 mCb.onDiscoverServicesStarted(listenerKey, info);
1953 } catch (RemoteException e) {
1954 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
1955 }
1956 }
1957
1958 void onDiscoverServicesFailed(int listenerKey, int error) {
1959 try {
1960 mCb.onDiscoverServicesFailed(listenerKey, error);
1961 } catch (RemoteException e) {
1962 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
1963 }
1964 }
1965
1966 void onServiceFound(int listenerKey, NsdServiceInfo info) {
1967 try {
1968 mCb.onServiceFound(listenerKey, info);
1969 } catch (RemoteException e) {
1970 Log.e(TAG, "Error calling onServiceFound(", e);
1971 }
1972 }
1973
1974 void onServiceLost(int listenerKey, NsdServiceInfo info) {
1975 try {
1976 mCb.onServiceLost(listenerKey, info);
1977 } catch (RemoteException e) {
1978 Log.e(TAG, "Error calling onServiceLost(", e);
1979 }
1980 }
1981
1982 void onStopDiscoveryFailed(int listenerKey, int error) {
1983 try {
1984 mCb.onStopDiscoveryFailed(listenerKey, error);
1985 } catch (RemoteException e) {
1986 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
1987 }
1988 }
1989
1990 void onStopDiscoverySucceeded(int listenerKey) {
1991 try {
1992 mCb.onStopDiscoverySucceeded(listenerKey);
1993 } catch (RemoteException e) {
1994 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
1995 }
1996 }
1997
1998 void onRegisterServiceFailed(int listenerKey, int error) {
1999 try {
2000 mCb.onRegisterServiceFailed(listenerKey, error);
2001 } catch (RemoteException e) {
2002 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2003 }
2004 }
2005
2006 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info) {
2007 try {
2008 mCb.onRegisterServiceSucceeded(listenerKey, info);
2009 } catch (RemoteException e) {
2010 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2011 }
2012 }
2013
2014 void onUnregisterServiceFailed(int listenerKey, int error) {
2015 try {
2016 mCb.onUnregisterServiceFailed(listenerKey, error);
2017 } catch (RemoteException e) {
2018 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2019 }
2020 }
2021
2022 void onUnregisterServiceSucceeded(int listenerKey) {
2023 try {
2024 mCb.onUnregisterServiceSucceeded(listenerKey);
2025 } catch (RemoteException e) {
2026 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2027 }
2028 }
2029
2030 void onResolveServiceFailed(int listenerKey, int error) {
2031 try {
2032 mCb.onResolveServiceFailed(listenerKey, error);
2033 } catch (RemoteException e) {
2034 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2035 }
2036 }
2037
2038 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info) {
2039 try {
2040 mCb.onResolveServiceSucceeded(listenerKey, info);
2041 } catch (RemoteException e) {
2042 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2043 }
2044 }
Paul Hub58deb72022-12-26 09:24:42 +00002045
2046 void onStopResolutionFailed(int listenerKey, int error) {
2047 try {
2048 mCb.onStopResolutionFailed(listenerKey, error);
2049 } catch (RemoteException e) {
2050 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2051 }
2052 }
2053
2054 void onStopResolutionSucceeded(int listenerKey) {
2055 try {
2056 mCb.onStopResolutionSucceeded(listenerKey);
2057 } catch (RemoteException e) {
2058 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2059 }
2060 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002061
2062 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
2063 try {
2064 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2065 } catch (RemoteException e) {
2066 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2067 }
2068 }
2069
2070 void onServiceUpdated(int listenerKey, NsdServiceInfo info) {
2071 try {
2072 mCb.onServiceUpdated(listenerKey, info);
2073 } catch (RemoteException e) {
2074 Log.e(TAG, "Error calling onServiceUpdated", e);
2075 }
2076 }
2077
2078 void onServiceUpdatedLost(int listenerKey) {
2079 try {
2080 mCb.onServiceUpdatedLost(listenerKey);
2081 } catch (RemoteException e) {
2082 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2083 }
2084 }
2085
2086 void onServiceInfoCallbackUnregistered(int listenerKey) {
2087 try {
2088 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2089 } catch (RemoteException e) {
2090 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2091 }
2092 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002093 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002094}