blob: 1e0d544b68e0463f0be95abc2ba2180a79f26cd7 [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;
Paul Hu14667de2023-04-17 22:42:47 +0800145 private static final SharedLog LOGGER = new SharedLog("serviceDiscovery");
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700146
Hugo Benichi32be63d2017-04-05 14:06:11 +0900147 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900148 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +0800149 private final MDnsManager mMDnsManager;
150 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900151 @NonNull
152 private final Dependencies mDeps;
153 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800154 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900155 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800156 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900157 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800158 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900159 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900160 private final MdnsAdvertiser mAdvertiser;
Paul Hu14667de2023-04-17 22:42:47 +0800161 private final SharedLog mServiceLogs = LOGGER.forSubComponent(TAG);
Paul Hu23fa2022023-01-13 22:57:24 +0800162 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800163 // state machine thread. If change this outside state machine, it will need to introduce
164 // synchronization.
165 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800166 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700167
168 /**
169 * Clients receiving asynchronous messages
170 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900171 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700172
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700173 /* A map from unique id to client info */
Hugo Benichi32be63d2017-04-05 14:06:11 +0900174 private final SparseArray<ClientInfo> mIdToClientInfoMap= new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700175
Luke Huang05298582021-06-13 16:52:05 +0000176 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700177
Hugo Benichi32be63d2017-04-05 14:06:11 +0900178 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700179 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800180 // The count of the connected legacy clients.
181 private int mLegacyClientCount = 0;
Paul Hub2e67d32023-04-18 05:50:14 +0000182 // The number of client that ever connected.
183 private int mClientNumberId = 1;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700184
Paul Hu23fa2022023-01-13 22:57:24 +0800185 private static class MdnsListener implements MdnsServiceBrowserListener {
186 protected final int mClientId;
187 protected final int mTransactionId;
188 @NonNull
189 protected final NsdServiceInfo mReqServiceInfo;
190 @NonNull
191 protected final String mListenedServiceType;
192
193 MdnsListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
194 @NonNull String listenedServiceType) {
195 mClientId = clientId;
196 mTransactionId = transactionId;
197 mReqServiceInfo = reqServiceInfo;
198 mListenedServiceType = listenedServiceType;
199 }
200
201 @NonNull
202 public String getListenedServiceType() {
203 return mListenedServiceType;
204 }
205
206 @Override
207 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) { }
208
209 @Override
210 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
211
212 @Override
213 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
214
215 @Override
216 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) { }
217
218 @Override
219 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
220
221 @Override
222 public void onSearchStoppedWithError(int error) { }
223
224 @Override
225 public void onSearchFailedToStart() { }
226
227 @Override
228 public void onDiscoveryQuerySent(@NonNull List<String> subtypes, int transactionId) { }
229
230 @Override
231 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
232 }
233
234 private class DiscoveryListener extends MdnsListener {
235
236 DiscoveryListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
237 @NonNull String listenServiceType) {
238 super(clientId, transactionId, reqServiceInfo, listenServiceType);
239 }
240
241 @Override
242 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu019621e2023-01-13 23:26:49 +0800243 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
244 NsdManager.SERVICE_FOUND,
245 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800246 }
247
248 @Override
249 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800250 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
251 NsdManager.SERVICE_LOST,
252 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800253 }
254 }
255
Paul Hu75069ed2023-01-14 00:31:09 +0800256 private class ResolutionListener extends MdnsListener {
257
258 ResolutionListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
259 @NonNull String listenServiceType) {
260 super(clientId, transactionId, reqServiceInfo, listenServiceType);
261 }
262
263 @Override
264 public void onServiceFound(MdnsServiceInfo serviceInfo) {
265 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
266 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
267 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
268 }
269 }
270
Paul Hu30bd70d2023-02-07 13:20:56 +0000271 private class ServiceInfoListener extends MdnsListener {
272
273 ServiceInfoListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
274 @NonNull String listenServiceType) {
275 super(clientId, transactionId, reqServiceInfo, listenServiceType);
276 }
277
278 @Override
279 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) {
280 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
281 NsdManager.SERVICE_UPDATED,
282 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
283 }
284
285 @Override
286 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) {
287 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
288 NsdManager.SERVICE_UPDATED,
289 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
290 }
291
292 @Override
293 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) {
294 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
295 NsdManager.SERVICE_UPDATED_LOST,
296 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
297 }
298 }
299
Paul Hu019621e2023-01-13 23:26:49 +0800300 /**
301 * Data class of mdns service callback information.
302 */
303 private static class MdnsEvent {
304 final int mClientId;
305 @NonNull
306 final String mRequestedServiceType;
307 @NonNull
308 final MdnsServiceInfo mMdnsServiceInfo;
309
310 MdnsEvent(int clientId, @NonNull String requestedServiceType,
311 @NonNull MdnsServiceInfo mdnsServiceInfo) {
312 mClientId = clientId;
313 mRequestedServiceType = requestedServiceType;
314 mMdnsServiceInfo = mdnsServiceInfo;
315 }
316 }
317
Irfan Sheriff75006652012-04-17 23:15:29 -0700318 private class NsdStateMachine extends StateMachine {
319
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700320 private final DefaultState mDefaultState = new DefaultState();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700321 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700322
323 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700324 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900325 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700326 }
327
Luke Huang92860f92021-06-23 06:29:30 +0000328 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800329 if (mIsDaemonStarted) {
330 if (DBG) Log.d(TAG, "Daemon is already started.");
331 return;
332 }
333 mMDnsManager.registerEventListener(mMDnsEventCallback);
334 mMDnsManager.startDaemon();
335 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000336 maybeScheduleStop();
Paul Hub2e67d32023-04-18 05:50:14 +0000337 mServiceLogs.log("Start mdns_responder daemon");
Luke Huang05298582021-06-13 16:52:05 +0000338 }
339
paulhu2b9ed952022-02-10 21:58:32 +0800340 private void maybeStopDaemon() {
341 if (!mIsDaemonStarted) {
342 if (DBG) Log.d(TAG, "Daemon has not been started.");
343 return;
344 }
345 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
346 mMDnsManager.stopDaemon();
347 mIsDaemonStarted = false;
Paul Hub2e67d32023-04-18 05:50:14 +0000348 mServiceLogs.log("Stop mdns_responder daemon");
paulhu2b9ed952022-02-10 21:58:32 +0800349 }
350
Luke Huang92860f92021-06-23 06:29:30 +0000351 private boolean isAnyRequestActive() {
352 return mIdToClientInfoMap.size() != 0;
353 }
354
355 private void scheduleStop() {
356 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
357 }
358 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800359 // The native daemon should stay alive and can't be cleanup
360 // if any legacy client connected.
361 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000362 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000363 }
364 }
365
Luke Huang92860f92021-06-23 06:29:30 +0000366 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000367 this.removeMessages(NsdManager.DAEMON_CLEANUP);
368 }
369
Paul Hu23fa2022023-01-13 22:57:24 +0800370 private void maybeStartMonitoringSockets() {
371 if (mIsMonitoringSocketsStarted) {
372 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
373 return;
374 }
375
376 mMdnsSocketProvider.startMonitoringSockets();
377 mIsMonitoringSocketsStarted = true;
378 }
379
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900380 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
381 if (!mIsMonitoringSocketsStarted) return;
382 if (isAnyRequestActive()) return;
383
Paul Hu58f20602023-02-18 11:41:07 +0800384 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800385 mIsMonitoringSocketsStarted = false;
386 }
387
Hugo Benichi803a2f02017-04-24 11:35:06 +0900388 NsdStateMachine(String name, Handler handler) {
389 super(name, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700390 addState(mDefaultState);
Irfan Sheriff75006652012-04-17 23:15:29 -0700391 addState(mEnabledState, mDefaultState);
paulhu5568f452021-11-30 13:31:29 +0800392 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900393 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700394 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700395 }
396
397 class DefaultState extends State {
398 @Override
399 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900400 final ClientInfo cInfo;
401 final int clientId = msg.arg2;
Irfan Sheriff75006652012-04-17 23:15:29 -0700402 switch (msg.what) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900403 case NsdManager.REGISTER_CLIENT:
Paul Hu2e0a88c2023-03-09 16:05:01 +0800404 final ConnectorArgs arg = (ConnectorArgs) msg.obj;
405 final INsdManagerCallback cb = arg.callback;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900406 try {
Paul Hu2e0a88c2023-03-09 16:05:01 +0800407 cb.asBinder().linkToDeath(arg.connector, 0);
Paul Hub2e67d32023-04-18 05:50:14 +0000408 final String tag = "Client" + arg.uid + "-" + mClientNumberId++;
409 cInfo = new ClientInfo(cb, arg.useJavaBackend,
410 mServiceLogs.forSubComponent(tag));
Paul Hu2e0a88c2023-03-09 16:05:01 +0800411 mClients.put(arg.connector, cInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900412 } catch (RemoteException e) {
413 Log.w(TAG, "Client " + clientId + " has already died");
Irfan Sheriff75006652012-04-17 23:15:29 -0700414 }
415 break;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900416 case NsdManager.UNREGISTER_CLIENT:
417 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
418 cInfo = mClients.remove(connector);
Dave Plattfeff2af2014-03-07 14:48:22 -0800419 if (cInfo != null) {
420 cInfo.expungeAllRequests();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900421 if (cInfo.isPreSClient()) {
Luke Huangf7277ed2021-07-12 21:15:10 +0800422 mLegacyClientCount -= 1;
423 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800424 }
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900425 maybeStopMonitoringSocketsIfNoActiveRequest();
Luke Huangf7277ed2021-07-12 21:15:10 +0800426 maybeScheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700427 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700428 case NsdManager.DISCOVER_SERVICES:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900429 cInfo = getClientInfoForReply(msg);
430 if (cInfo != null) {
431 cInfo.onDiscoverServicesFailed(
432 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
433 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700434 break;
435 case NsdManager.STOP_DISCOVERY:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900436 cInfo = getClientInfoForReply(msg);
437 if (cInfo != null) {
438 cInfo.onStopDiscoveryFailed(
439 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
440 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700441 break;
442 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900443 cInfo = getClientInfoForReply(msg);
444 if (cInfo != null) {
445 cInfo.onRegisterServiceFailed(
446 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
447 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700448 break;
449 case NsdManager.UNREGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900450 cInfo = getClientInfoForReply(msg);
451 if (cInfo != null) {
452 cInfo.onUnregisterServiceFailed(
453 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
454 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700455 break;
456 case NsdManager.RESOLVE_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900457 cInfo = getClientInfoForReply(msg);
458 if (cInfo != null) {
459 cInfo.onResolveServiceFailed(
460 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
461 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700462 break;
Paul Hub58deb72022-12-26 09:24:42 +0000463 case NsdManager.STOP_RESOLUTION:
464 cInfo = getClientInfoForReply(msg);
465 if (cInfo != null) {
466 cInfo.onStopResolutionFailed(
467 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
468 }
469 break;
Paul Hu18aeccc2022-12-27 08:48:48 +0000470 case NsdManager.REGISTER_SERVICE_CALLBACK:
471 cInfo = getClientInfoForReply(msg);
472 if (cInfo != null) {
473 cInfo.onServiceInfoCallbackRegistrationFailed(
474 clientId, NsdManager.FAILURE_BAD_PARAMETERS);
475 }
476 break;
Luke Huang05298582021-06-13 16:52:05 +0000477 case NsdManager.DAEMON_CLEANUP:
paulhu2b9ed952022-02-10 21:58:32 +0800478 maybeStopDaemon();
Luke Huang05298582021-06-13 16:52:05 +0000479 break;
Luke Huangf7277ed2021-07-12 21:15:10 +0800480 // This event should be only sent by the legacy (target SDK < S) clients.
481 // Mark the sending client as legacy.
482 case NsdManager.DAEMON_STARTUP:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900483 cInfo = getClientInfoForReply(msg);
Luke Huangf7277ed2021-07-12 21:15:10 +0800484 if (cInfo != null) {
485 cancelStop();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900486 cInfo.setPreSClient();
Luke Huangf7277ed2021-07-12 21:15:10 +0800487 mLegacyClientCount += 1;
488 maybeStartDaemon();
489 }
490 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700491 default:
paulhub2225702021-11-17 09:35:33 +0800492 Log.e(TAG, "Unhandled " + msg);
Irfan Sheriff75006652012-04-17 23:15:29 -0700493 return NOT_HANDLED;
494 }
495 return HANDLED;
496 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900497
498 private ClientInfo getClientInfoForReply(Message msg) {
499 final ListenerArgs args = (ListenerArgs) msg.obj;
500 return mClients.get(args.connector);
501 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700502 }
503
Irfan Sheriff75006652012-04-17 23:15:29 -0700504 class EnabledState extends State {
505 @Override
506 public void enter() {
507 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700508 }
509
510 @Override
511 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000512 // TODO: it is incorrect to stop the daemon without expunging all requests
513 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000514 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700515 }
516
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700517 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900518 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800519 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700520 return true;
521 }
522 return false;
523 }
524
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900525 private void storeLegacyRequestMap(int clientId, int globalId, ClientInfo clientInfo,
526 int what) {
527 clientInfo.mClientRequests.put(clientId, new LegacyClientRequest(globalId, what));
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700528 mIdToClientInfoMap.put(globalId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000529 // Remove the cleanup event because here comes a new request.
530 cancelStop();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700531 }
532
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900533 private void storeAdvertiserRequestMap(int clientId, int globalId,
Paul Hu23fa2022023-01-13 22:57:24 +0800534 ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900535 clientInfo.mClientRequests.put(clientId, new AdvertiserClientRequest(globalId));
536 mIdToClientInfoMap.put(globalId, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800537 }
538
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900539 private void removeRequestMap(int clientId, int globalId, ClientInfo clientInfo) {
540 final ClientRequest existing = clientInfo.mClientRequests.get(clientId);
541 if (existing == null) return;
542 clientInfo.mClientRequests.remove(clientId);
543 mIdToClientInfoMap.remove(globalId);
544
545 if (existing instanceof LegacyClientRequest) {
546 maybeScheduleStop();
547 } else {
548 maybeStopMonitoringSocketsIfNoActiveRequest();
549 }
550 }
551
552 private void storeDiscoveryManagerRequestMap(int clientId, int globalId,
553 MdnsListener listener, ClientInfo clientInfo) {
554 clientInfo.mClientRequests.put(clientId,
555 new DiscoveryManagerRequest(globalId, listener));
556 mIdToClientInfoMap.put(globalId, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800557 }
558
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900559 /**
560 * Truncate a service name to up to 63 UTF-8 bytes.
561 *
562 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
563 * names used in registerService follows historical behavior (see mdnsresponder
564 * handle_regservice_request).
565 */
566 @NonNull
567 private String truncateServiceName(@NonNull String originalName) {
Yuyang Huangde802c82023-05-02 17:14:22 +0900568 return MdnsUtils.truncateServiceName(originalName, MAX_LABEL_LENGTH);
Paul Hu23fa2022023-01-13 22:57:24 +0800569 }
570
Paul Hue4f5f252023-02-16 21:13:47 +0800571 private void stopDiscoveryManagerRequest(ClientRequest request, int clientId, int id,
572 ClientInfo clientInfo) {
573 clientInfo.unregisterMdnsListenerFromRequest(request);
574 removeRequestMap(clientId, id, clientInfo);
575 }
576
Irfan Sheriff75006652012-04-17 23:15:29 -0700577 @Override
578 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900579 final ClientInfo clientInfo;
580 final int id;
581 final int clientId = msg.arg2;
582 final ListenerArgs args;
Irfan Sheriff75006652012-04-17 23:15:29 -0700583 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800584 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800585 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900586 args = (ListenerArgs) msg.obj;
587 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000588 // If the binder death notification for a INsdManagerCallback was received
589 // before any calls are received by NsdService, the clientInfo would be
590 // cleared and cause NPE. Add a null check here to prevent this corner case.
591 if (clientInfo == null) {
592 Log.e(TAG, "Unknown connector in discovery");
593 break;
594 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700595
596 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900597 clientInfo.onDiscoverServicesFailed(
598 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriff75006652012-04-17 23:15:29 -0700599 break;
600 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700601
Paul Hu23fa2022023-01-13 22:57:24 +0800602 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700603 id = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900604 final String serviceType = constructServiceType(info.getServiceType());
Paul Hu2e0a88c2023-03-09 16:05:01 +0800605 if (clientInfo.mUseJavaBackend
606 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900607 || useDiscoveryManagerForType(serviceType)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800608 if (serviceType == null) {
609 clientInfo.onDiscoverServicesFailed(clientId,
610 NsdManager.FAILURE_INTERNAL_ERROR);
611 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700612 }
Paul Hu23fa2022023-01-13 22:57:24 +0800613
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900614 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800615 maybeStartMonitoringSockets();
616 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900617 new DiscoveryListener(clientId, id, info, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800618 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
619 .setNetwork(info.getNetwork())
620 .setIsPassiveMode(true)
621 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900622 mMdnsDiscoveryManager.registerListener(
623 listenServiceType, listener, options);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900624 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800625 clientInfo.onDiscoverServicesStarted(clientId, info);
Paul Hub2e67d32023-04-18 05:50:14 +0000626 clientInfo.log("Register a DiscoveryListener " + id
627 + " for service type:" + listenServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700628 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800629 maybeStartDaemon();
630 if (discoverServices(id, info)) {
631 if (DBG) {
632 Log.d(TAG, "Discover " + msg.arg2 + " " + id
633 + info.getServiceType());
634 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900635 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu23fa2022023-01-13 22:57:24 +0800636 clientInfo.onDiscoverServicesStarted(clientId, info);
637 } else {
638 stopServiceDiscovery(id);
639 clientInfo.onDiscoverServicesFailed(clientId,
640 NsdManager.FAILURE_INTERNAL_ERROR);
641 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700642 }
643 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800644 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900645 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800646 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900647 args = (ListenerArgs) msg.obj;
648 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000649 // If the binder death notification for a INsdManagerCallback was received
650 // before any calls are received by NsdService, the clientInfo would be
651 // cleared and cause NPE. Add a null check here to prevent this corner case.
652 if (clientInfo == null) {
653 Log.e(TAG, "Unknown connector in stop discovery");
654 break;
655 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700656
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900657 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
658 if (request == null) {
659 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700660 break;
661 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900662 id = request.mGlobalId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900663 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
664 // point, so this needs to check the type of the original request to
665 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900666 if (request instanceof DiscoveryManagerRequest) {
Paul Hue4f5f252023-02-16 21:13:47 +0800667 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900668 clientInfo.onStopDiscoverySucceeded(clientId);
Paul Hub2e67d32023-04-18 05:50:14 +0000669 clientInfo.log("Unregister the DiscoveryListener " + id);
Irfan Sheriff75006652012-04-17 23:15:29 -0700670 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800671 removeRequestMap(clientId, id, clientInfo);
672 if (stopServiceDiscovery(id)) {
673 clientInfo.onStopDiscoverySucceeded(clientId);
674 } else {
675 clientInfo.onStopDiscoveryFailed(
676 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
677 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700678 }
679 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900680 }
681 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800682 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900683 args = (ListenerArgs) msg.obj;
684 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000685 // If the binder death notification for a INsdManagerCallback was received
686 // before any calls are received by NsdService, the clientInfo would be
687 // cleared and cause NPE. Add a null check here to prevent this corner case.
688 if (clientInfo == null) {
689 Log.e(TAG, "Unknown connector in registration");
690 break;
691 }
692
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700693 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900694 clientInfo.onRegisterServiceFailed(
695 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700696 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700697 }
698
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700699 id = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900700 final NsdServiceInfo serviceInfo = args.serviceInfo;
701 final String serviceType = serviceInfo.getServiceType();
702 final String registerServiceType = constructServiceType(serviceType);
Paul Hu2e0a88c2023-03-09 16:05:01 +0800703 if (clientInfo.mUseJavaBackend
704 || mDeps.isMdnsAdvertiserEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900705 || useAdvertiserForType(registerServiceType)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900706 if (registerServiceType == null) {
707 Log.e(TAG, "Invalid service type: " + serviceType);
708 clientInfo.onRegisterServiceFailed(clientId,
709 NsdManager.FAILURE_INTERNAL_ERROR);
710 break;
711 }
712 serviceInfo.setServiceType(registerServiceType);
713 serviceInfo.setServiceName(truncateServiceName(
714 serviceInfo.getServiceName()));
715
716 maybeStartMonitoringSockets();
717 mAdvertiser.addService(id, serviceInfo);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900718 storeAdvertiserRequestMap(clientId, id, clientInfo);
Irfan Sheriff75006652012-04-17 23:15:29 -0700719 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900720 maybeStartDaemon();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900721 if (registerService(id, serviceInfo)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900722 if (DBG) Log.d(TAG, "Register " + clientId + " " + id);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900723 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900724 // Return success after mDns reports success
725 } else {
726 unregisterService(id);
727 clientInfo.onRegisterServiceFailed(
728 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
729 }
730
Irfan Sheriff75006652012-04-17 23:15:29 -0700731 }
732 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900733 }
734 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800735 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900736 args = (ListenerArgs) msg.obj;
737 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000738 // If the binder death notification for a INsdManagerCallback was received
739 // before any calls are received by NsdService, the clientInfo would be
740 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900741 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800742 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700743 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700744 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900745 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
746 if (request == null) {
747 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
748 break;
749 }
750 id = request.mGlobalId;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900751 removeRequestMap(clientId, id, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900752
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900753 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
754 // so this needs to check the type of the original request to unregister
755 // instead of looking at the flag value.
756 if (request instanceof AdvertiserClientRequest) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900757 mAdvertiser.removeService(id);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900758 clientInfo.onUnregisterServiceSucceeded(clientId);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700759 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900760 if (unregisterService(id)) {
761 clientInfo.onUnregisterServiceSucceeded(clientId);
762 } else {
763 clientInfo.onUnregisterServiceFailed(
764 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
765 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700766 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700767 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900768 }
Paul Hu75069ed2023-01-14 00:31:09 +0800769 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800770 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900771 args = (ListenerArgs) msg.obj;
772 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000773 // If the binder death notification for a INsdManagerCallback was received
774 // before any calls are received by NsdService, the clientInfo would be
775 // cleared and cause NPE. Add a null check here to prevent this corner case.
776 if (clientInfo == null) {
777 Log.e(TAG, "Unknown connector in resolution");
778 break;
779 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700780
Paul Hu75069ed2023-01-14 00:31:09 +0800781 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700782 id = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900783 final String serviceType = constructServiceType(info.getServiceType());
Paul Hu2e0a88c2023-03-09 16:05:01 +0800784 if (clientInfo.mUseJavaBackend
785 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900786 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800787 if (serviceType == null) {
788 clientInfo.onResolveServiceFailed(clientId,
789 NsdManager.FAILURE_INTERNAL_ERROR);
790 break;
791 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900792 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +0800793
794 maybeStartMonitoringSockets();
795 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900796 new ResolutionListener(clientId, id, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800797 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
798 .setNetwork(info.getNetwork())
799 .setIsPassiveMode(true)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900800 .setResolveInstanceName(info.getServiceName())
Paul Hu75069ed2023-01-14 00:31:09 +0800801 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900802 mMdnsDiscoveryManager.registerListener(
803 resolveServiceType, listener, options);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900804 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Paul Hub2e67d32023-04-18 05:50:14 +0000805 clientInfo.log("Register a ResolutionListener " + id
806 + " for service type:" + resolveServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700807 } else {
Paul Hu75069ed2023-01-14 00:31:09 +0800808 if (clientInfo.mResolvedService != null) {
809 clientInfo.onResolveServiceFailed(
810 clientId, NsdManager.FAILURE_ALREADY_ACTIVE);
811 break;
812 }
813
814 maybeStartDaemon();
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900815 if (resolveService(id, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800816 clientInfo.mResolvedService = new NsdServiceInfo();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900817 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu75069ed2023-01-14 00:31:09 +0800818 } else {
819 clientInfo.onResolveServiceFailed(
820 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
821 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700822 }
823 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800824 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900825 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +0000826 if (DBG) Log.d(TAG, "Stop service resolution");
827 args = (ListenerArgs) msg.obj;
828 clientInfo = mClients.get(args.connector);
829 // If the binder death notification for a INsdManagerCallback was received
830 // before any calls are received by NsdService, the clientInfo would be
831 // cleared and cause NPE. Add a null check here to prevent this corner case.
832 if (clientInfo == null) {
833 Log.e(TAG, "Unknown connector in stop resolution");
834 break;
835 }
836
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900837 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
838 if (request == null) {
839 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
840 break;
841 }
842 id = request.mGlobalId;
Paul Hue4f5f252023-02-16 21:13:47 +0800843 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
844 // point, so this needs to check the type of the original request to
845 // unregister instead of looking at the flag value.
846 if (request instanceof DiscoveryManagerRequest) {
847 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Paul Hub58deb72022-12-26 09:24:42 +0000848 clientInfo.onStopResolutionSucceeded(clientId);
Paul Hub2e67d32023-04-18 05:50:14 +0000849 clientInfo.log("Unregister the ResolutionListener " + id);
Paul Hub58deb72022-12-26 09:24:42 +0000850 } else {
Paul Hue4f5f252023-02-16 21:13:47 +0800851 removeRequestMap(clientId, id, clientInfo);
852 if (stopResolveService(id)) {
853 clientInfo.onStopResolutionSucceeded(clientId);
854 } else {
855 clientInfo.onStopResolutionFailed(
856 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
857 }
858 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +0000859 }
Paul Hub58deb72022-12-26 09:24:42 +0000860 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900861 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000862 case NsdManager.REGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +0000863 if (DBG) Log.d(TAG, "Register a service callback");
864 args = (ListenerArgs) msg.obj;
865 clientInfo = mClients.get(args.connector);
866 // If the binder death notification for a INsdManagerCallback was received
867 // before any calls are received by NsdService, the clientInfo would be
868 // cleared and cause NPE. Add a null check here to prevent this corner case.
869 if (clientInfo == null) {
870 Log.e(TAG, "Unknown connector in callback registration");
871 break;
872 }
873
Paul Hu30bd70d2023-02-07 13:20:56 +0000874 final NsdServiceInfo info = args.serviceInfo;
875 id = getUniqueId();
876 final String serviceType = constructServiceType(info.getServiceType());
877 if (serviceType == null) {
878 clientInfo.onServiceInfoCallbackRegistrationFailed(clientId,
879 NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +0000880 break;
881 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000882 final String resolveServiceType = serviceType + ".local";
Paul Hu18aeccc2022-12-27 08:48:48 +0000883
Paul Hu30bd70d2023-02-07 13:20:56 +0000884 maybeStartMonitoringSockets();
885 final MdnsListener listener =
886 new ServiceInfoListener(clientId, id, info, resolveServiceType);
887 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
888 .setNetwork(info.getNetwork())
889 .setIsPassiveMode(true)
890 .setResolveInstanceName(info.getServiceName())
891 .build();
892 mMdnsDiscoveryManager.registerListener(
893 resolveServiceType, listener, options);
894 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Paul Hub2e67d32023-04-18 05:50:14 +0000895 clientInfo.log("Register a ServiceInfoListener " + id
896 + " for service type:" + resolveServiceType);
Paul Hu18aeccc2022-12-27 08:48:48 +0000897 break;
Paul Hu30bd70d2023-02-07 13:20:56 +0000898 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900899 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +0000900 if (DBG) Log.d(TAG, "Unregister a service callback");
901 args = (ListenerArgs) msg.obj;
902 clientInfo = mClients.get(args.connector);
903 // If the binder death notification for a INsdManagerCallback was received
904 // before any calls are received by NsdService, the clientInfo would be
905 // cleared and cause NPE. Add a null check here to prevent this corner case.
906 if (clientInfo == null) {
907 Log.e(TAG, "Unknown connector in callback unregistration");
908 break;
909 }
910
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900911 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
912 if (request == null) {
Paul Hu30bd70d2023-02-07 13:20:56 +0000913 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE_CALLBACK");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900914 break;
915 }
916 id = request.mGlobalId;
Paul Hu30bd70d2023-02-07 13:20:56 +0000917 if (request instanceof DiscoveryManagerRequest) {
918 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Paul Hu18aeccc2022-12-27 08:48:48 +0000919 clientInfo.onServiceInfoCallbackUnregistered(clientId);
Paul Hub2e67d32023-04-18 05:50:14 +0000920 clientInfo.log("Unregister the ServiceInfoListener " + id);
Paul Hu18aeccc2022-12-27 08:48:48 +0000921 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +0000922 loge("Unregister failed with non-DiscoveryManagerRequest.");
Paul Hu18aeccc2022-12-27 08:48:48 +0000923 }
Paul Hu18aeccc2022-12-27 08:48:48 +0000924 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900925 }
paulhu2b9ed952022-02-10 21:58:32 +0800926 case MDNS_SERVICE_EVENT:
927 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +0900928 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700929 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700930 break;
Paul Hu019621e2023-01-13 23:26:49 +0800931 case MDNS_DISCOVERY_MANAGER_EVENT:
932 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
933 return NOT_HANDLED;
934 }
935 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700936 default:
Hugo Benichif0c84092017-04-05 14:43:29 +0900937 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700938 }
Hugo Benichif0c84092017-04-05 14:43:29 +0900939 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700940 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700941
paulhu2b9ed952022-02-10 21:58:32 +0800942 private boolean handleMDnsServiceEvent(int code, int id, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700943 NsdServiceInfo servInfo;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700944 ClientInfo clientInfo = mIdToClientInfoMap.get(id);
945 if (clientInfo == null) {
paulhu2b9ed952022-02-10 21:58:32 +0800946 Log.e(TAG, String.format("id %d for %d has no client mapping", id, code));
Hugo Benichif0c84092017-04-05 14:43:29 +0900947 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700948 }
949
950 /* This goes in response as msg.arg2 */
Christopher Lane74411222014-04-25 18:39:07 -0700951 int clientId = clientInfo.getClientId(id);
952 if (clientId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -0700953 // This can happen because of race conditions. For example,
954 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
955 // and we may get in this situation.
paulhu2b9ed952022-02-10 21:58:32 +0800956 Log.d(TAG, String.format("%d for listener id %d that is no longer active",
957 code, id));
Hugo Benichif0c84092017-04-05 14:43:29 +0900958 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700959 }
Hugo Benichi32be63d2017-04-05 14:06:11 +0900960 if (DBG) {
paulhu2b9ed952022-02-10 21:58:32 +0800961 Log.d(TAG, String.format("MDns service event code:%d id=%d", code, id));
Hugo Benichi32be63d2017-04-05 14:06:11 +0900962 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700963 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +0800964 case IMDnsEventListener.SERVICE_FOUND: {
965 final DiscoveryInfo info = (DiscoveryInfo) obj;
966 final String name = info.serviceName;
967 final String type = info.registrationType;
968 servInfo = new NsdServiceInfo(name, type);
969 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900970 if (foundNetId == 0L) {
971 // Ignore services that do not have a Network: they are not usable
972 // by apps, as they would need privileged permissions to use
973 // interfaces that do not have an associated Network.
974 break;
975 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +0900976 if (foundNetId == INetd.DUMMY_NET_ID) {
977 // Ignore services on the dummy0 interface: they are only seen when
978 // discovering locally advertised services, and are not reachable
979 // through that interface.
980 break;
981 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900982 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900983 clientInfo.onServiceFound(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700984 break;
paulhu2b9ed952022-02-10 21:58:32 +0800985 }
986 case IMDnsEventListener.SERVICE_LOST: {
987 final DiscoveryInfo info = (DiscoveryInfo) obj;
988 final String name = info.serviceName;
989 final String type = info.registrationType;
990 final int lostNetId = info.netId;
991 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900992 // The network could be set to null (netId 0) if it was torn down when the
993 // service is lost
994 // TODO: avoid returning null in that case, possibly by remembering
995 // found services on the same interface index and their network at the time
996 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900997 clientInfo.onServiceLost(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700998 break;
paulhu2b9ed952022-02-10 21:58:32 +0800999 }
1000 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001001 clientInfo.onDiscoverServicesFailed(
1002 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001003 break;
paulhu2b9ed952022-02-10 21:58:32 +08001004 case IMDnsEventListener.SERVICE_REGISTERED: {
1005 final RegistrationInfo info = (RegistrationInfo) obj;
1006 final String name = info.serviceName;
1007 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001008 clientInfo.onRegisterServiceSucceeded(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001009 break;
paulhu2b9ed952022-02-10 21:58:32 +08001010 }
1011 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001012 clientInfo.onRegisterServiceFailed(
1013 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001014 break;
paulhu2b9ed952022-02-10 21:58:32 +08001015 case IMDnsEventListener.SERVICE_RESOLVED: {
1016 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001017 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +08001018 final String fullName = info.serviceFullName;
1019 while (index < fullName.length() && fullName.charAt(index) != '.') {
1020 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001021 ++index;
1022 }
1023 ++index;
1024 }
paulhu2b9ed952022-02-10 21:58:32 +08001025 if (index >= fullName.length()) {
1026 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001027 break;
1028 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001029
paulhube186602022-04-12 07:18:23 +00001030 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001031 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001032 String type = rest.replace(".local.", "");
1033
Paul Hu30bd70d2023-02-07 13:20:56 +00001034 final NsdServiceInfo serviceInfo = clientInfo.mResolvedService;
Paul Hu18aeccc2022-12-27 08:48:48 +00001035 serviceInfo.setServiceName(name);
1036 serviceInfo.setServiceType(type);
1037 serviceInfo.setPort(info.port);
1038 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001039 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001040
1041 stopResolveService(id);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001042 removeRequestMap(clientId, id, clientInfo);
1043
paulhu2b9ed952022-02-10 21:58:32 +08001044 final int id2 = getUniqueId();
1045 if (getAddrInfo(id2, info.hostname, info.interfaceIdx)) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001046 storeLegacyRequestMap(clientId, id2, clientInfo,
1047 NsdManager.RESOLVE_SERVICE);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001048 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001049 clientInfo.onResolveServiceFailed(
1050 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1051 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001052 }
1053 break;
paulhu2b9ed952022-02-10 21:58:32 +08001054 }
1055 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001056 /* NNN resolveId errorCode */
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001057 stopResolveService(id);
1058 removeRequestMap(clientId, id, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001059 clientInfo.onResolveServiceFailed(
1060 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1061 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001062 break;
paulhu2b9ed952022-02-10 21:58:32 +08001063 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001064 /* NNN resolveId errorCode */
1065 stopGetAddrInfo(id);
1066 removeRequestMap(clientId, id, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001067 clientInfo.onResolveServiceFailed(
1068 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1069 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001070 break;
paulhu2b9ed952022-02-10 21:58:32 +08001071 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001072 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001073 final GetAddressInfo info = (GetAddressInfo) obj;
1074 final String address = info.address;
1075 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001076 InetAddress serviceHost = null;
1077 try {
paulhu2b9ed952022-02-10 21:58:32 +08001078 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001079 } catch (UnknownHostException e) {
1080 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1081 }
1082
1083 // If the resolved service is on an interface without a network, consider it
1084 // as a failure: it would not be usable by apps as they would need
1085 // privileged permissions.
Paul Hu30bd70d2023-02-07 13:20:56 +00001086 if (netId != NETID_UNSET && serviceHost != null) {
1087 clientInfo.mResolvedService.setHost(serviceHost);
1088 setServiceNetworkForCallback(clientInfo.mResolvedService,
1089 netId, info.interfaceIdx);
1090 clientInfo.onResolveServiceSucceeded(
1091 clientId, clientInfo.mResolvedService);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001092 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001093 clientInfo.onResolveServiceFailed(
1094 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001095 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001096 stopGetAddrInfo(id);
1097 removeRequestMap(clientId, id, clientInfo);
1098 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001099 break;
paulhu2b9ed952022-02-10 21:58:32 +08001100 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001101 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001102 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001103 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001104 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001105 }
Paul Hu019621e2023-01-13 23:26:49 +08001106
1107 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(final MdnsEvent event) {
1108 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1109 final String serviceType = event.mRequestedServiceType;
1110 final String serviceName = serviceInfo.getServiceInstanceName();
1111 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1112 final Network network = serviceInfo.getNetwork();
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001113 // In MdnsDiscoveryManagerEvent, the Network can be null which means it is a
1114 // network for Tethering interface. In other words, the network == null means the
1115 // network has netId = INetd.LOCAL_NET_ID.
Paul Hu019621e2023-01-13 23:26:49 +08001116 setServiceNetworkForCallback(
1117 servInfo,
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001118 network == null ? INetd.LOCAL_NET_ID : network.netId,
Paul Hu019621e2023-01-13 23:26:49 +08001119 serviceInfo.getInterfaceIndex());
1120 return servInfo;
1121 }
1122
1123 private boolean handleMdnsDiscoveryManagerEvent(
1124 int transactionId, int code, Object obj) {
1125 final ClientInfo clientInfo = mIdToClientInfoMap.get(transactionId);
1126 if (clientInfo == null) {
1127 Log.e(TAG, String.format(
1128 "id %d for %d has no client mapping", transactionId, code));
1129 return false;
1130 }
1131
1132 final MdnsEvent event = (MdnsEvent) obj;
1133 final int clientId = event.mClientId;
Paul Hu319751a2023-01-13 23:56:34 +08001134 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event);
Paul Hu019621e2023-01-13 23:26:49 +08001135 if (DBG) {
1136 Log.d(TAG, String.format("MdnsDiscoveryManager event code=%s transactionId=%d",
1137 NsdManager.nameOf(code), transactionId));
1138 }
1139 switch (code) {
1140 case NsdManager.SERVICE_FOUND:
Paul Hu319751a2023-01-13 23:56:34 +08001141 clientInfo.onServiceFound(clientId, info);
1142 break;
1143 case NsdManager.SERVICE_LOST:
1144 clientInfo.onServiceLost(clientId, info);
Paul Hu019621e2023-01-13 23:26:49 +08001145 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001146 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001147 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
1148 if (request == null) {
1149 Log.e(TAG, "Unknown client request in RESOLVE_SERVICE_SUCCEEDED");
1150 break;
1151 }
Paul Hu75069ed2023-01-14 00:31:09 +08001152 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1153 // Add '.' in front of the service type that aligns with historical behavior
1154 info.setServiceType("." + event.mRequestedServiceType);
1155 info.setPort(serviceInfo.getPort());
1156
1157 Map<String, String> attrs = serviceInfo.getAttributes();
1158 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1159 final String key = kv.getKey();
1160 try {
1161 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1162 } catch (IllegalArgumentException e) {
1163 Log.e(TAG, "Invalid attribute", e);
1164 }
1165 }
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001166 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu2b865912023-03-06 14:27:53 +08001167 if (addresses.size() != 0) {
1168 info.setHostAddresses(addresses);
Paul Hu75069ed2023-01-14 00:31:09 +08001169 clientInfo.onResolveServiceSucceeded(clientId, info);
Paul Hu2b865912023-03-06 14:27:53 +08001170 } else {
1171 // No address. Notify resolution failure.
Paul Hu75069ed2023-01-14 00:31:09 +08001172 clientInfo.onResolveServiceFailed(
1173 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1174 }
1175
1176 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001177 if (!(request instanceof DiscoveryManagerRequest)) {
1178 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1179 break;
1180 }
Paul Hue4f5f252023-02-16 21:13:47 +08001181 stopDiscoveryManagerRequest(request, clientId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001182 break;
1183 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001184 case NsdManager.SERVICE_UPDATED: {
1185 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1186 info.setPort(serviceInfo.getPort());
1187
1188 Map<String, String> attrs = serviceInfo.getAttributes();
1189 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1190 final String key = kv.getKey();
1191 try {
1192 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1193 } catch (IllegalArgumentException e) {
1194 Log.e(TAG, "Invalid attribute", e);
1195 }
1196 }
1197
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001198 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001199 info.setHostAddresses(addresses);
1200 clientInfo.onServiceUpdated(clientId, info);
1201 break;
1202 }
1203 case NsdManager.SERVICE_UPDATED_LOST:
1204 clientInfo.onServiceUpdatedLost(clientId);
1205 break;
Paul Hu019621e2023-01-13 23:26:49 +08001206 default:
1207 return false;
1208 }
1209 return true;
1210 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001211 }
1212 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001213
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001214 @NonNull
1215 private static List<InetAddress> getInetAddresses(@NonNull MdnsServiceInfo serviceInfo) {
1216 final List<String> v4Addrs = serviceInfo.getIpv4Addresses();
1217 final List<String> v6Addrs = serviceInfo.getIpv6Addresses();
1218 final List<InetAddress> addresses = new ArrayList<>(v4Addrs.size() + v6Addrs.size());
1219 for (String ipv4Address : v4Addrs) {
1220 try {
1221 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1222 } catch (IllegalArgumentException e) {
1223 Log.wtf(TAG, "Invalid ipv4 address", e);
1224 }
1225 }
1226 for (String ipv6Address : v6Addrs) {
1227 try {
Yuyang Huanga6a6ff92023-04-24 13:33:34 +09001228 final Inet6Address addr = (Inet6Address) InetAddresses.parseNumericAddress(
1229 ipv6Address);
1230 addresses.add(InetAddressUtils.withScopeId(addr, serviceInfo.getInterfaceIndex()));
1231 } catch (IllegalArgumentException e) {
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001232 Log.wtf(TAG, "Invalid ipv6 address", e);
1233 }
1234 }
1235 return addresses;
1236 }
1237
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001238 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1239 switch (netId) {
1240 case NETID_UNSET:
1241 info.setNetwork(null);
1242 break;
1243 case INetd.LOCAL_NET_ID:
1244 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1245 // visible / usable for apps, so do not return it. Store the interface
1246 // index instead, so at least if the client tries to resolve the service
1247 // with that NsdServiceInfo, it will be done on the same interface.
1248 // If they recreate the NsdServiceInfo themselves, resolution would be
1249 // done on all interfaces as before T, which should also work.
1250 info.setNetwork(null);
1251 info.setInterfaceIndex(ifaceIdx);
1252 break;
1253 default:
1254 info.setNetwork(new Network(netId));
1255 }
1256 }
1257
paulhube186602022-04-12 07:18:23 +00001258 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1259 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1260 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1261 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1262 private String unescape(String s) {
1263 StringBuilder sb = new StringBuilder(s.length());
1264 for (int i = 0; i < s.length(); ++i) {
1265 char c = s.charAt(i);
1266 if (c == '\\') {
1267 if (++i >= s.length()) {
1268 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1269 break;
1270 }
1271 c = s.charAt(i);
1272 if (c != '.' && c != '\\') {
1273 if (i + 2 >= s.length()) {
1274 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1275 break;
1276 }
1277 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1278 + (s.charAt(i + 2) - '0'));
1279 i += 2;
1280 }
1281 }
1282 sb.append(c);
1283 }
1284 return sb.toString();
1285 }
1286
Paul Hu7445e3d2023-03-03 15:14:00 +08001287 /**
1288 * Check the given service type is valid and construct it to a service type
1289 * which can use for discovery / resolution service.
1290 *
1291 * <p> The valid service type should be 2 labels, or 3 labels if the query is for a
1292 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1293 * underscore; they are alphanumerical characters or dashes or underscore, except the
1294 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1295 *
1296 * @param serviceType the request service type for discovery / resolution service
1297 * @return constructed service type or null if the given service type is invalid.
1298 */
1299 @Nullable
1300 public static String constructServiceType(String serviceType) {
1301 if (TextUtils.isEmpty(serviceType)) return null;
1302
1303 final Pattern serviceTypePattern = Pattern.compile(
1304 "^(_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]\\.)?"
1305 + "(_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]\\._(?:tcp|udp))"
1306 // Drop '.' at the end of service type that is compatible with old backend.
1307 + "\\.?$");
1308 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1309 if (!matcher.matches()) return null;
1310 return matcher.group(1) == null
1311 ? matcher.group(2)
1312 : matcher.group(1) + "_sub." + matcher.group(2);
1313 }
1314
Hugo Benichi803a2f02017-04-24 11:35:06 +09001315 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001316 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001317 this(ctx, handler, cleanupDelayMs, new Dependencies());
1318 }
1319
1320 @VisibleForTesting
1321 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001322 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001323 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001324 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001325 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001326 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1327 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001328 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001329
Paul Hu14667de2023-04-17 22:42:47 +08001330 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper(),
1331 LOGGER.forSubComponent("MdnsSocketProvider"));
Yuyang Huang700778b2023-03-08 16:17:05 +09001332 // Netlink monitor starts on boot, and intentionally never stopped, to ensure that all
1333 // address events are received.
1334 handler.post(mMdnsSocketProvider::startNetLinkMonitor);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001335 mMdnsSocketClient =
1336 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider);
Paul Hu14667de2023-04-17 22:42:47 +08001337 mMdnsDiscoveryManager = deps.makeMdnsDiscoveryManager(new ExecutorProvider(),
1338 mMdnsSocketClient, LOGGER.forSubComponent("MdnsDiscoveryManager"));
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001339 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1340 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
Paul Hu14667de2023-04-17 22:42:47 +08001341 new AdvertiserCallback(), LOGGER.forSubComponent("MdnsAdvertiser"));
Paul Hu4bd98ef2023-01-12 13:42:07 +08001342 }
1343
1344 /**
1345 * Dependencies of NsdService, for injection in tests.
1346 */
1347 @VisibleForTesting
1348 public static class Dependencies {
1349 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001350 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001351 *
1352 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001353 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001354 */
1355 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi278db582023-04-21 12:35:22 +09001356 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1357 MDNS_DISCOVERY_MANAGER_VERSION, DeviceConfigUtils.TETHERING_MODULE_NAME,
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +09001358 false /* defaultEnabled */);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001359 }
1360
1361 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001362 * Check whether the MdnsAdvertiser feature is enabled.
1363 *
1364 * @param context The global context information about an app environment.
1365 * @return true if the MdnsAdvertiser feature is enabled.
1366 */
1367 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi278db582023-04-21 12:35:22 +09001368 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1369 MDNS_ADVERTISER_VERSION, DeviceConfigUtils.TETHERING_MODULE_NAME,
1370 false /* defaultEnabled */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001371 }
1372
1373 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001374 * Get the type allowlist flag value.
1375 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1376 */
1377 @Nullable
1378 public String getTypeAllowlistFlags() {
1379 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1380 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1381 }
1382
1383 /**
1384 * @see DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)
1385 */
1386 public boolean isFeatureEnabled(Context context, String feature) {
1387 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1388 feature, DeviceConfigUtils.TETHERING_MODULE_NAME, false /* defaultEnabled */);
1389 }
1390
1391 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001392 * @see MdnsDiscoveryManager
1393 */
1394 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
Paul Hu14667de2023-04-17 22:42:47 +08001395 @NonNull ExecutorProvider executorProvider,
1396 @NonNull MdnsSocketClientBase socketClient, @NonNull SharedLog sharedLog) {
1397 return new MdnsDiscoveryManager(executorProvider, socketClient, sharedLog);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001398 }
1399
1400 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001401 * @see MdnsAdvertiser
1402 */
1403 public MdnsAdvertiser makeMdnsAdvertiser(
1404 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
Paul Hu14667de2023-04-17 22:42:47 +08001405 @NonNull MdnsAdvertiser.AdvertiserCallback cb, @NonNull SharedLog sharedLog) {
1406 return new MdnsAdvertiser(looper, socketProvider, cb, sharedLog);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001407 }
1408
1409 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001410 * @see MdnsSocketProvider
1411 */
Paul Hu14667de2023-04-17 22:42:47 +08001412 public MdnsSocketProvider makeMdnsSocketProvider(@NonNull Context context,
1413 @NonNull Looper looper, @NonNull SharedLog sharedLog) {
1414 return new MdnsSocketProvider(context, looper, sharedLog);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001415 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001416 }
1417
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001418 /**
1419 * Return whether a type is allowlisted to use the Java backend.
1420 * @param type The service type
1421 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1422 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1423 */
1424 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1425 @NonNull String flagPrefix) {
1426 if (type == null) return false;
1427 final String typesConfig = mDeps.getTypeAllowlistFlags();
1428 if (TextUtils.isEmpty(typesConfig)) return false;
1429
1430 final String mappingPrefix = type + ":";
1431 String mappedFlag = null;
1432 for (String mapping : TextUtils.split(typesConfig, ",")) {
1433 if (mapping.startsWith(mappingPrefix)) {
1434 mappedFlag = mapping.substring(mappingPrefix.length());
1435 break;
1436 }
1437 }
1438
1439 if (mappedFlag == null) return false;
1440
1441 return mDeps.isFeatureEnabled(mContext,
1442 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1443 }
1444
1445 private boolean useDiscoveryManagerForType(@Nullable String type) {
1446 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1447 }
1448
1449 private boolean useAdvertiserForType(@Nullable String type) {
1450 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1451 }
1452
paulhu1b35e822022-04-08 14:48:41 +08001453 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001454 HandlerThread thread = new HandlerThread(TAG);
1455 thread.start();
1456 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001457 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001458 return service;
1459 }
1460
paulhu2b9ed952022-02-10 21:58:32 +08001461 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1462 private final StateMachine mStateMachine;
1463
1464 MDnsEventCallback(StateMachine sm) {
1465 mStateMachine = sm;
1466 }
1467
1468 @Override
1469 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1470 mStateMachine.sendMessage(
1471 MDNS_SERVICE_EVENT, status.result, status.id, status);
1472 }
1473
1474 @Override
1475 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1476 mStateMachine.sendMessage(
1477 MDNS_SERVICE_EVENT, status.result, status.id, status);
1478 }
1479
1480 @Override
1481 public void onServiceResolutionStatus(final ResolutionInfo status) {
1482 mStateMachine.sendMessage(
1483 MDNS_SERVICE_EVENT, status.result, status.id, status);
1484 }
1485
1486 @Override
1487 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1488 mStateMachine.sendMessage(
1489 MDNS_SERVICE_EVENT, status.result, status.id, status);
1490 }
1491
1492 @Override
1493 public int getInterfaceVersion() throws RemoteException {
1494 return this.VERSION;
1495 }
1496
1497 @Override
1498 public String getInterfaceHash() throws RemoteException {
1499 return this.HASH;
1500 }
1501 }
1502
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001503 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
1504 @Override
1505 public void onRegisterServiceSucceeded(int serviceId, NsdServiceInfo registeredInfo) {
1506 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1507 if (clientInfo == null) return;
1508
1509 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1510 if (clientId < 0) return;
1511
1512 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1513 // historical behavior.
1514 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
1515 clientInfo.onRegisterServiceSucceeded(clientId, cbInfo);
1516 }
1517
1518 @Override
1519 public void onRegisterServiceFailed(int serviceId, int errorCode) {
1520 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1521 if (clientInfo == null) return;
1522
1523 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1524 if (clientId < 0) return;
1525
1526 clientInfo.onRegisterServiceFailed(clientId, errorCode);
1527 }
1528
1529 private ClientInfo getClientInfoOrLog(int serviceId) {
1530 final ClientInfo clientInfo = mIdToClientInfoMap.get(serviceId);
1531 if (clientInfo == null) {
1532 Log.e(TAG, String.format("Callback for service %d has no client", serviceId));
1533 }
1534 return clientInfo;
1535 }
1536
1537 private int getClientIdOrLog(@NonNull ClientInfo info, int serviceId) {
1538 final int clientId = info.getClientId(serviceId);
1539 if (clientId < 0) {
1540 Log.e(TAG, String.format("Client ID not found for service %d", serviceId));
1541 }
1542 return clientId;
1543 }
1544 }
1545
Paul Hu2e0a88c2023-03-09 16:05:01 +08001546 private static class ConnectorArgs {
1547 @NonNull public final NsdServiceConnector connector;
1548 @NonNull public final INsdManagerCallback callback;
1549 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001550 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001551
1552 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00001553 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08001554 this.connector = connector;
1555 this.callback = callback;
1556 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001557 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001558 }
1559 }
1560
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001561 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08001562 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001563 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu2e0a88c2023-03-09 16:05:01 +08001564 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001565 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00001566 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
1567 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend,
1568 Binder.getCallingUid())));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001569 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07001570 }
1571
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001572 private static class ListenerArgs {
1573 public final NsdServiceConnector connector;
1574 public final NsdServiceInfo serviceInfo;
1575 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
1576 this.connector = connector;
1577 this.serviceInfo = serviceInfo;
1578 }
1579 }
1580
1581 private class NsdServiceConnector extends INsdServiceConnector.Stub
1582 implements IBinder.DeathRecipient {
1583 @Override
1584 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
1585 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1586 NsdManager.REGISTER_SERVICE, 0, listenerKey,
1587 new ListenerArgs(this, serviceInfo)));
1588 }
1589
1590 @Override
1591 public void unregisterService(int listenerKey) {
1592 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1593 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
1594 new ListenerArgs(this, null)));
1595 }
1596
1597 @Override
1598 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
1599 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1600 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
1601 new ListenerArgs(this, serviceInfo)));
1602 }
1603
1604 @Override
1605 public void stopDiscovery(int listenerKey) {
1606 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1607 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
1608 }
1609
1610 @Override
1611 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
1612 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1613 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
1614 new ListenerArgs(this, serviceInfo)));
1615 }
1616
1617 @Override
Paul Hub58deb72022-12-26 09:24:42 +00001618 public void stopResolution(int listenerKey) {
1619 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1620 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
1621 }
1622
1623 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00001624 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
1625 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1626 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
1627 new ListenerArgs(this, serviceInfo)));
1628 }
1629
1630 @Override
1631 public void unregisterServiceInfoCallback(int listenerKey) {
1632 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1633 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
1634 new ListenerArgs(this, null)));
1635 }
1636
1637 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001638 public void startDaemon() {
1639 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1640 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
1641 }
1642
1643 @Override
1644 public void binderDied() {
1645 mNsdStateMachine.sendMessage(
1646 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
1647 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001648 }
1649
Hugo Benichi912db992017-04-24 16:41:03 +09001650 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07001651 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07001652 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09001653 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
1654 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07001655 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07001656 }
1657
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001658 private int getUniqueId() {
1659 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
1660 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001661 }
1662
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001663 private boolean registerService(int regId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09001664 if (DBG) {
paulhub2225702021-11-17 09:35:33 +08001665 Log.d(TAG, "registerService: " + regId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001666 }
Hugo Benichi6d706442017-04-24 16:19:58 +09001667 String name = service.getServiceName();
1668 String type = service.getServiceType();
1669 int port = service.getPort();
1670 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001671 final int registerInterface = getNetworkInterfaceIndex(service);
1672 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08001673 Log.e(TAG, "Interface to register service on not found");
1674 return false;
1675 }
1676 return mMDnsManager.registerService(regId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001677 }
1678
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001679 private boolean unregisterService(int regId) {
paulhu2b9ed952022-02-10 21:58:32 +08001680 return mMDnsManager.stopOperation(regId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001681 }
1682
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001683 private boolean discoverServices(int discoveryId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08001684 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001685 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
1686 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001687 Log.e(TAG, "Interface to discover service on not found");
1688 return false;
1689 }
paulhu2b9ed952022-02-10 21:58:32 +08001690 return mMDnsManager.discover(discoveryId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001691 }
1692
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001693 private boolean stopServiceDiscovery(int discoveryId) {
paulhu2b9ed952022-02-10 21:58:32 +08001694 return mMDnsManager.stopOperation(discoveryId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001695 }
1696
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001697 private boolean resolveService(int resolveId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001698 final String name = service.getServiceName();
1699 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001700 final int resolveInterface = getNetworkInterfaceIndex(service);
1701 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001702 Log.e(TAG, "Interface to resolve service on not found");
1703 return false;
1704 }
paulhu2b9ed952022-02-10 21:58:32 +08001705 return mMDnsManager.resolve(resolveId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001706 }
1707
1708 /**
1709 * Guess the interface to use to resolve or discover a service on a specific network.
1710 *
1711 * This is an imperfect guess, as for example the network may be gone or not yet fully
1712 * registered. This is fine as failing is correct if the network is gone, and a client
1713 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
1714 * this is to support the legacy mdnsresponder implementation, which historically resolved
1715 * services on an unspecified network.
1716 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001717 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
1718 final Network network = serviceInfo.getNetwork();
1719 if (network == null) {
1720 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
1721 // provided by NsdService from discovery results, and the service was found on an
1722 // interface that has no app-usable Network).
1723 if (serviceInfo.getInterfaceIndex() != 0) {
1724 return serviceInfo.getInterfaceIndex();
1725 }
1726 return IFACE_IDX_ANY;
1727 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001728
1729 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
1730 if (cm == null) {
1731 Log.wtf(TAG, "No ConnectivityManager for resolveService");
1732 return IFACE_IDX_ANY;
1733 }
1734 final LinkProperties lp = cm.getLinkProperties(network);
1735 if (lp == null) return IFACE_IDX_ANY;
1736
1737 // Only resolve on non-stacked interfaces
1738 final NetworkInterface iface;
1739 try {
1740 iface = NetworkInterface.getByName(lp.getInterfaceName());
1741 } catch (SocketException e) {
1742 Log.e(TAG, "Error querying interface", e);
1743 return IFACE_IDX_ANY;
1744 }
1745
1746 if (iface == null) {
1747 Log.e(TAG, "Interface not found: " + lp.getInterfaceName());
1748 return IFACE_IDX_ANY;
1749 }
1750
1751 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001752 }
1753
1754 private boolean stopResolveService(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001755 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001756 }
1757
paulhu2b9ed952022-02-10 21:58:32 +08001758 private boolean getAddrInfo(int resolveId, String hostname, int interfaceIdx) {
1759 return mMDnsManager.getServiceAddress(resolveId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001760 }
1761
1762 private boolean stopGetAddrInfo(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001763 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001764 }
1765
1766 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00001767 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1768 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001769
Paul Hub2e67d32023-04-18 05:50:14 +00001770 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
1771 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07001772 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00001773
1774 // Dump service and clients logs
1775 pw.println();
Paul Hu14667de2023-04-17 22:42:47 +08001776 pw.println("Logs:");
Paul Hub2e67d32023-04-18 05:50:14 +00001777 pw.increaseIndent();
1778 mServiceLogs.reverseDump(pw);
1779 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001780 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001781
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001782 private abstract static class ClientRequest {
1783 private final int mGlobalId;
1784
1785 private ClientRequest(int globalId) {
1786 mGlobalId = globalId;
1787 }
1788 }
1789
1790 private static class LegacyClientRequest extends ClientRequest {
1791 private final int mRequestCode;
1792
1793 private LegacyClientRequest(int globalId, int requestCode) {
1794 super(globalId);
1795 mRequestCode = requestCode;
1796 }
1797 }
1798
1799 private static class AdvertiserClientRequest extends ClientRequest {
1800 private AdvertiserClientRequest(int globalId) {
1801 super(globalId);
1802 }
1803 }
1804
1805 private static class DiscoveryManagerRequest extends ClientRequest {
1806 @NonNull
1807 private final MdnsListener mListener;
1808
1809 private DiscoveryManagerRequest(int globalId, @NonNull MdnsListener listener) {
1810 super(globalId);
1811 mListener = listener;
1812 }
1813 }
1814
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001815 /* Information tracked per client */
1816 private class ClientInfo {
1817
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001818 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001819 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001820 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001821 private NsdServiceInfo mResolvedService;
1822
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001823 /* A map from client-side ID (listenerKey) to the request */
1824 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08001825
Luke Huangf7277ed2021-07-12 21:15:10 +08001826 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001827 private boolean mIsPreSClient = false;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001828 // The flag of using java backend if the client's target SDK >= U
1829 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001830 // Store client logs
1831 private final SharedLog mClientLogs;
Luke Huangf7277ed2021-07-12 21:15:10 +08001832
Paul Hub2e67d32023-04-18 05:50:14 +00001833 private ClientInfo(INsdManagerCallback cb, boolean useJavaBackend, SharedLog sharedLog) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001834 mCb = cb;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001835 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001836 mClientLogs = sharedLog;
1837 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001838 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001839
1840 @Override
1841 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06001842 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07001843 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001844 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
1845 for (int i = 0; i < mClientRequests.size(); i++) {
1846 int clientID = mClientRequests.keyAt(i);
1847 sb.append("clientId ")
1848 .append(clientID)
1849 .append(" mDnsId ").append(mClientRequests.valueAt(i).mGlobalId)
1850 .append(" type ").append(
1851 mClientRequests.valueAt(i).getClass().getSimpleName())
1852 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07001853 }
1854 return sb.toString();
1855 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001856
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001857 private boolean isPreSClient() {
1858 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08001859 }
1860
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001861 private void setPreSClient() {
1862 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08001863 }
1864
Paul Hue4f5f252023-02-16 21:13:47 +08001865 private void unregisterMdnsListenerFromRequest(ClientRequest request) {
1866 final MdnsListener listener =
1867 ((DiscoveryManagerRequest) request).mListener;
1868 mMdnsDiscoveryManager.unregisterListener(
1869 listener.getListenedServiceType(), listener);
1870 }
1871
Dave Plattfeff2af2014-03-07 14:48:22 -08001872 // Remove any pending requests from the global map when we get rid of a client,
1873 // and send cancellations to the daemon.
1874 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00001875 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09001876 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001877 for (int i = 0; i < mClientRequests.size(); i++) {
1878 final int clientId = mClientRequests.keyAt(i);
1879 final ClientRequest request = mClientRequests.valueAt(i);
1880 final int globalId = request.mGlobalId;
Dave Plattfeff2af2014-03-07 14:48:22 -08001881 mIdToClientInfoMap.remove(globalId);
paulhub2225702021-11-17 09:35:33 +08001882 if (DBG) {
1883 Log.d(TAG, "Terminating client-ID " + clientId
1884 + " global-ID " + globalId + " type " + mClientRequests.get(clientId));
1885 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001886
1887 if (request instanceof DiscoveryManagerRequest) {
Paul Hue4f5f252023-02-16 21:13:47 +08001888 unregisterMdnsListenerFromRequest(request);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001889 continue;
1890 }
1891
1892 if (request instanceof AdvertiserClientRequest) {
1893 mAdvertiser.removeService(globalId);
1894 continue;
1895 }
1896
1897 if (!(request instanceof LegacyClientRequest)) {
1898 throw new IllegalStateException("Unknown request type: " + request.getClass());
1899 }
1900
1901 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08001902 case NsdManager.DISCOVER_SERVICES:
1903 stopServiceDiscovery(globalId);
1904 break;
1905 case NsdManager.RESOLVE_SERVICE:
1906 stopResolveService(globalId);
1907 break;
1908 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001909 unregisterService(globalId);
Dave Plattfeff2af2014-03-07 14:48:22 -08001910 break;
1911 default:
1912 break;
1913 }
1914 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001915 mClientRequests.clear();
1916 }
1917
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001918 // mClientRequests is a sparse array of listener id -> ClientRequest. For a given
1919 // mDnsClient id, return the corresponding listener id. mDnsClient id is also called a
1920 // global id.
Christopher Lane74411222014-04-25 18:39:07 -07001921 private int getClientId(final int globalId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001922 for (int i = 0; i < mClientRequests.size(); i++) {
1923 if (mClientRequests.valueAt(i).mGlobalId == globalId) {
1924 return mClientRequests.keyAt(i);
1925 }
Christopher Lane74411222014-04-25 18:39:07 -07001926 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001927 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07001928 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001929
Paul Hub2e67d32023-04-18 05:50:14 +00001930 private void log(String message) {
1931 mClientLogs.log(message);
1932 }
1933
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001934 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info) {
1935 try {
1936 mCb.onDiscoverServicesStarted(listenerKey, info);
1937 } catch (RemoteException e) {
1938 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
1939 }
1940 }
1941
1942 void onDiscoverServicesFailed(int listenerKey, int error) {
1943 try {
1944 mCb.onDiscoverServicesFailed(listenerKey, error);
1945 } catch (RemoteException e) {
1946 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
1947 }
1948 }
1949
1950 void onServiceFound(int listenerKey, NsdServiceInfo info) {
1951 try {
1952 mCb.onServiceFound(listenerKey, info);
1953 } catch (RemoteException e) {
1954 Log.e(TAG, "Error calling onServiceFound(", e);
1955 }
1956 }
1957
1958 void onServiceLost(int listenerKey, NsdServiceInfo info) {
1959 try {
1960 mCb.onServiceLost(listenerKey, info);
1961 } catch (RemoteException e) {
1962 Log.e(TAG, "Error calling onServiceLost(", e);
1963 }
1964 }
1965
1966 void onStopDiscoveryFailed(int listenerKey, int error) {
1967 try {
1968 mCb.onStopDiscoveryFailed(listenerKey, error);
1969 } catch (RemoteException e) {
1970 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
1971 }
1972 }
1973
1974 void onStopDiscoverySucceeded(int listenerKey) {
1975 try {
1976 mCb.onStopDiscoverySucceeded(listenerKey);
1977 } catch (RemoteException e) {
1978 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
1979 }
1980 }
1981
1982 void onRegisterServiceFailed(int listenerKey, int error) {
1983 try {
1984 mCb.onRegisterServiceFailed(listenerKey, error);
1985 } catch (RemoteException e) {
1986 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
1987 }
1988 }
1989
1990 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info) {
1991 try {
1992 mCb.onRegisterServiceSucceeded(listenerKey, info);
1993 } catch (RemoteException e) {
1994 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
1995 }
1996 }
1997
1998 void onUnregisterServiceFailed(int listenerKey, int error) {
1999 try {
2000 mCb.onUnregisterServiceFailed(listenerKey, error);
2001 } catch (RemoteException e) {
2002 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2003 }
2004 }
2005
2006 void onUnregisterServiceSucceeded(int listenerKey) {
2007 try {
2008 mCb.onUnregisterServiceSucceeded(listenerKey);
2009 } catch (RemoteException e) {
2010 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2011 }
2012 }
2013
2014 void onResolveServiceFailed(int listenerKey, int error) {
2015 try {
2016 mCb.onResolveServiceFailed(listenerKey, error);
2017 } catch (RemoteException e) {
2018 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2019 }
2020 }
2021
2022 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info) {
2023 try {
2024 mCb.onResolveServiceSucceeded(listenerKey, info);
2025 } catch (RemoteException e) {
2026 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2027 }
2028 }
Paul Hub58deb72022-12-26 09:24:42 +00002029
2030 void onStopResolutionFailed(int listenerKey, int error) {
2031 try {
2032 mCb.onStopResolutionFailed(listenerKey, error);
2033 } catch (RemoteException e) {
2034 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2035 }
2036 }
2037
2038 void onStopResolutionSucceeded(int listenerKey) {
2039 try {
2040 mCb.onStopResolutionSucceeded(listenerKey);
2041 } catch (RemoteException e) {
2042 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2043 }
2044 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002045
2046 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
2047 try {
2048 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2049 } catch (RemoteException e) {
2050 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2051 }
2052 }
2053
2054 void onServiceUpdated(int listenerKey, NsdServiceInfo info) {
2055 try {
2056 mCb.onServiceUpdated(listenerKey, info);
2057 } catch (RemoteException e) {
2058 Log.e(TAG, "Error calling onServiceUpdated", e);
2059 }
2060 }
2061
2062 void onServiceUpdatedLost(int listenerKey) {
2063 try {
2064 mCb.onServiceUpdatedLost(listenerKey);
2065 } catch (RemoteException e) {
2066 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2067 }
2068 }
2069
2070 void onServiceInfoCallbackUnregistered(int listenerKey) {
2071 try {
2072 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2073 } catch (RemoteException e) {
2074 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2075 }
2076 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002077 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002078}