blob: a62ee7f73977dcd2837f4b7b755c7e9bba6ca622 [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;
Paul Hu4bd98ef2023-01-12 13:42:07 +080022import static android.provider.DeviceConfig.NAMESPACE_CONNECTIVITY;
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +090023import static android.provider.DeviceConfig.NAMESPACE_TETHERING;
paulhu2b9ed952022-02-10 21:58:32 +080024
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090025import static com.android.modules.utils.build.SdkLevel.isAtLeastU;
26
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;
paulhua262cc12019-08-12 16:25:11 +080076
Irfan Sheriff77ec5582012-03-22 17:01:39 -070077import java.io.FileDescriptor;
78import java.io.PrintWriter;
Yuyang Huangaa0e9602023-03-17 12:43:09 +090079import java.net.Inet6Address;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070080import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090081import java.net.NetworkInterface;
82import java.net.SocketException;
83import java.net.UnknownHostException;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090084import java.nio.ByteBuffer;
85import java.nio.CharBuffer;
86import java.nio.charset.Charset;
87import java.nio.charset.CharsetEncoder;
88import java.nio.charset.StandardCharsets;
Paul Hu2b865912023-03-06 14:27:53 +080089import java.util.ArrayList;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070090import java.util.HashMap;
Paul Hu23fa2022023-01-13 22:57:24 +080091import java.util.List;
Paul Hu75069ed2023-01-14 00:31:09 +080092import java.util.Map;
Paul Hu23fa2022023-01-13 22:57:24 +080093import java.util.regex.Matcher;
94import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070095
Irfan Sheriff77ec5582012-03-22 17:01:39 -070096/**
97 * Network Service Discovery Service handles remote service discovery operation requests by
98 * implementing the INsdManager interface.
99 *
100 * @hide
101 */
102public class NsdService extends INsdManager.Stub {
103 private static final String TAG = "NsdService";
104 private static final String MDNS_TAG = "mDnsConnector";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900105 /**
106 * Enable discovery using the Java DiscoveryManager, instead of the legacy mdnsresponder
107 * implementation.
108 */
Paul Hu4bd98ef2023-01-12 13:42:07 +0800109 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +0800110 private static final String LOCAL_DOMAIN_NAME = "local";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900111 // Max label length as per RFC 1034/1035
112 private static final int MAX_LABEL_LENGTH = 63;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700113
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900114 /**
115 * Enable advertising using the Java MdnsAdvertiser, instead of the legacy mdnsresponder
116 * implementation.
117 */
118 private static final String MDNS_ADVERTISER_VERSION = "mdns_advertiser_version";
119
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900120 /**
121 * Comma-separated list of type:flag mappings indicating the flags to use to allowlist
122 * discovery/advertising using MdnsDiscoveryManager / MdnsAdvertiser for a given type.
123 *
124 * For example _mytype._tcp.local and _othertype._tcp.local would be configured with:
125 * _mytype._tcp:mytype,_othertype._tcp.local:othertype
126 *
127 * In which case the flags:
128 * "mdns_discovery_manager_allowlist_mytype_version",
129 * "mdns_advertiser_allowlist_mytype_version",
130 * "mdns_discovery_manager_allowlist_othertype_version",
131 * "mdns_advertiser_allowlist_othertype_version"
132 * would be used to toggle MdnsDiscoveryManager / MdnsAdvertiser for each type. The flags will
133 * be read with
134 * {@link DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)}.
135 *
136 * @see #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX
137 * @see #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX
138 * @see #MDNS_ALLOWLIST_FLAG_SUFFIX
139 */
140 private static final String MDNS_TYPE_ALLOWLIST_FLAGS = "mdns_type_allowlist_flags";
141
142 private static final String MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX =
143 "mdns_discovery_manager_allowlist_";
144 private static final String MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX =
145 "mdns_advertiser_allowlist_";
146 private static final String MDNS_ALLOWLIST_FLAG_SUFFIX = "_version";
147
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900148 public static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +0000149 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900150 private static final int IFACE_IDX_ANY = 0;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700151
Hugo Benichi32be63d2017-04-05 14:06:11 +0900152 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900153 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +0800154 private final MDnsManager mMDnsManager;
155 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900156 @NonNull
157 private final Dependencies mDeps;
158 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800159 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900160 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800161 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900162 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800163 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900164 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900165 private final MdnsAdvertiser mAdvertiser;
Paul Hub2e67d32023-04-18 05:50:14 +0000166 private final SharedLog mServiceLogs = new SharedLog(TAG);
Paul Hu23fa2022023-01-13 22:57:24 +0800167 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800168 // state machine thread. If change this outside state machine, it will need to introduce
169 // synchronization.
170 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800171 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700172
173 /**
174 * Clients receiving asynchronous messages
175 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900176 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700177
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700178 /* A map from unique id to client info */
Hugo Benichi32be63d2017-04-05 14:06:11 +0900179 private final SparseArray<ClientInfo> mIdToClientInfoMap= new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700180
Luke Huang05298582021-06-13 16:52:05 +0000181 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700182
Hugo Benichi32be63d2017-04-05 14:06:11 +0900183 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700184 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800185 // The count of the connected legacy clients.
186 private int mLegacyClientCount = 0;
Paul Hub2e67d32023-04-18 05:50:14 +0000187 // The number of client that ever connected.
188 private int mClientNumberId = 1;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700189
Paul Hu23fa2022023-01-13 22:57:24 +0800190 private static class MdnsListener implements MdnsServiceBrowserListener {
191 protected final int mClientId;
192 protected final int mTransactionId;
193 @NonNull
194 protected final NsdServiceInfo mReqServiceInfo;
195 @NonNull
196 protected final String mListenedServiceType;
197
198 MdnsListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
199 @NonNull String listenedServiceType) {
200 mClientId = clientId;
201 mTransactionId = transactionId;
202 mReqServiceInfo = reqServiceInfo;
203 mListenedServiceType = listenedServiceType;
204 }
205
206 @NonNull
207 public String getListenedServiceType() {
208 return mListenedServiceType;
209 }
210
211 @Override
212 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) { }
213
214 @Override
215 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
216
217 @Override
218 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
219
220 @Override
221 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) { }
222
223 @Override
224 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
225
226 @Override
227 public void onSearchStoppedWithError(int error) { }
228
229 @Override
230 public void onSearchFailedToStart() { }
231
232 @Override
233 public void onDiscoveryQuerySent(@NonNull List<String> subtypes, int transactionId) { }
234
235 @Override
236 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
237 }
238
239 private class DiscoveryListener extends MdnsListener {
240
241 DiscoveryListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
242 @NonNull String listenServiceType) {
243 super(clientId, transactionId, reqServiceInfo, listenServiceType);
244 }
245
246 @Override
247 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu019621e2023-01-13 23:26:49 +0800248 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
249 NsdManager.SERVICE_FOUND,
250 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800251 }
252
253 @Override
254 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800255 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
256 NsdManager.SERVICE_LOST,
257 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800258 }
259 }
260
Paul Hu75069ed2023-01-14 00:31:09 +0800261 private class ResolutionListener extends MdnsListener {
262
263 ResolutionListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
264 @NonNull String listenServiceType) {
265 super(clientId, transactionId, reqServiceInfo, listenServiceType);
266 }
267
268 @Override
269 public void onServiceFound(MdnsServiceInfo serviceInfo) {
270 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
271 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
272 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
273 }
274 }
275
Paul Hu30bd70d2023-02-07 13:20:56 +0000276 private class ServiceInfoListener extends MdnsListener {
277
278 ServiceInfoListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
279 @NonNull String listenServiceType) {
280 super(clientId, transactionId, reqServiceInfo, listenServiceType);
281 }
282
283 @Override
284 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) {
285 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
286 NsdManager.SERVICE_UPDATED,
287 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
288 }
289
290 @Override
291 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) {
292 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
293 NsdManager.SERVICE_UPDATED,
294 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
295 }
296
297 @Override
298 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) {
299 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
300 NsdManager.SERVICE_UPDATED_LOST,
301 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
302 }
303 }
304
Paul Hu019621e2023-01-13 23:26:49 +0800305 /**
306 * Data class of mdns service callback information.
307 */
308 private static class MdnsEvent {
309 final int mClientId;
310 @NonNull
311 final String mRequestedServiceType;
312 @NonNull
313 final MdnsServiceInfo mMdnsServiceInfo;
314
315 MdnsEvent(int clientId, @NonNull String requestedServiceType,
316 @NonNull MdnsServiceInfo mdnsServiceInfo) {
317 mClientId = clientId;
318 mRequestedServiceType = requestedServiceType;
319 mMdnsServiceInfo = mdnsServiceInfo;
320 }
321 }
322
Irfan Sheriff75006652012-04-17 23:15:29 -0700323 private class NsdStateMachine extends StateMachine {
324
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700325 private final DefaultState mDefaultState = new DefaultState();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700326 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700327
328 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700329 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900330 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700331 }
332
Luke Huang92860f92021-06-23 06:29:30 +0000333 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800334 if (mIsDaemonStarted) {
335 if (DBG) Log.d(TAG, "Daemon is already started.");
336 return;
337 }
338 mMDnsManager.registerEventListener(mMDnsEventCallback);
339 mMDnsManager.startDaemon();
340 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000341 maybeScheduleStop();
Paul Hub2e67d32023-04-18 05:50:14 +0000342 mServiceLogs.log("Start mdns_responder daemon");
Luke Huang05298582021-06-13 16:52:05 +0000343 }
344
paulhu2b9ed952022-02-10 21:58:32 +0800345 private void maybeStopDaemon() {
346 if (!mIsDaemonStarted) {
347 if (DBG) Log.d(TAG, "Daemon has not been started.");
348 return;
349 }
350 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
351 mMDnsManager.stopDaemon();
352 mIsDaemonStarted = false;
Paul Hub2e67d32023-04-18 05:50:14 +0000353 mServiceLogs.log("Stop mdns_responder daemon");
paulhu2b9ed952022-02-10 21:58:32 +0800354 }
355
Luke Huang92860f92021-06-23 06:29:30 +0000356 private boolean isAnyRequestActive() {
357 return mIdToClientInfoMap.size() != 0;
358 }
359
360 private void scheduleStop() {
361 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
362 }
363 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800364 // The native daemon should stay alive and can't be cleanup
365 // if any legacy client connected.
366 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000367 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000368 }
369 }
370
Luke Huang92860f92021-06-23 06:29:30 +0000371 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000372 this.removeMessages(NsdManager.DAEMON_CLEANUP);
373 }
374
Paul Hu23fa2022023-01-13 22:57:24 +0800375 private void maybeStartMonitoringSockets() {
376 if (mIsMonitoringSocketsStarted) {
377 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
378 return;
379 }
380
381 mMdnsSocketProvider.startMonitoringSockets();
382 mIsMonitoringSocketsStarted = true;
383 }
384
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900385 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
386 if (!mIsMonitoringSocketsStarted) return;
387 if (isAnyRequestActive()) return;
388
Paul Hu58f20602023-02-18 11:41:07 +0800389 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800390 mIsMonitoringSocketsStarted = false;
391 }
392
Hugo Benichi803a2f02017-04-24 11:35:06 +0900393 NsdStateMachine(String name, Handler handler) {
394 super(name, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700395 addState(mDefaultState);
Irfan Sheriff75006652012-04-17 23:15:29 -0700396 addState(mEnabledState, mDefaultState);
paulhu5568f452021-11-30 13:31:29 +0800397 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900398 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700399 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700400 }
401
402 class DefaultState extends State {
403 @Override
404 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900405 final ClientInfo cInfo;
406 final int clientId = msg.arg2;
Irfan Sheriff75006652012-04-17 23:15:29 -0700407 switch (msg.what) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900408 case NsdManager.REGISTER_CLIENT:
Paul Hu2e0a88c2023-03-09 16:05:01 +0800409 final ConnectorArgs arg = (ConnectorArgs) msg.obj;
410 final INsdManagerCallback cb = arg.callback;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900411 try {
Paul Hu2e0a88c2023-03-09 16:05:01 +0800412 cb.asBinder().linkToDeath(arg.connector, 0);
Paul Hub2e67d32023-04-18 05:50:14 +0000413 final String tag = "Client" + arg.uid + "-" + mClientNumberId++;
414 cInfo = new ClientInfo(cb, arg.useJavaBackend,
415 mServiceLogs.forSubComponent(tag));
Paul Hu2e0a88c2023-03-09 16:05:01 +0800416 mClients.put(arg.connector, cInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900417 } catch (RemoteException e) {
418 Log.w(TAG, "Client " + clientId + " has already died");
Irfan Sheriff75006652012-04-17 23:15:29 -0700419 }
420 break;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900421 case NsdManager.UNREGISTER_CLIENT:
422 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
423 cInfo = mClients.remove(connector);
Dave Plattfeff2af2014-03-07 14:48:22 -0800424 if (cInfo != null) {
425 cInfo.expungeAllRequests();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900426 if (cInfo.isPreSClient()) {
Luke Huangf7277ed2021-07-12 21:15:10 +0800427 mLegacyClientCount -= 1;
428 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800429 }
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900430 maybeStopMonitoringSocketsIfNoActiveRequest();
Luke Huangf7277ed2021-07-12 21:15:10 +0800431 maybeScheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700432 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700433 case NsdManager.DISCOVER_SERVICES:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900434 cInfo = getClientInfoForReply(msg);
435 if (cInfo != null) {
436 cInfo.onDiscoverServicesFailed(
437 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
438 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700439 break;
440 case NsdManager.STOP_DISCOVERY:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900441 cInfo = getClientInfoForReply(msg);
442 if (cInfo != null) {
443 cInfo.onStopDiscoveryFailed(
444 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
445 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700446 break;
447 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900448 cInfo = getClientInfoForReply(msg);
449 if (cInfo != null) {
450 cInfo.onRegisterServiceFailed(
451 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
452 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700453 break;
454 case NsdManager.UNREGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900455 cInfo = getClientInfoForReply(msg);
456 if (cInfo != null) {
457 cInfo.onUnregisterServiceFailed(
458 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
459 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700460 break;
461 case NsdManager.RESOLVE_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900462 cInfo = getClientInfoForReply(msg);
463 if (cInfo != null) {
464 cInfo.onResolveServiceFailed(
465 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
466 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700467 break;
Paul Hub58deb72022-12-26 09:24:42 +0000468 case NsdManager.STOP_RESOLUTION:
469 cInfo = getClientInfoForReply(msg);
470 if (cInfo != null) {
471 cInfo.onStopResolutionFailed(
472 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
473 }
474 break;
Paul Hu18aeccc2022-12-27 08:48:48 +0000475 case NsdManager.REGISTER_SERVICE_CALLBACK:
476 cInfo = getClientInfoForReply(msg);
477 if (cInfo != null) {
478 cInfo.onServiceInfoCallbackRegistrationFailed(
479 clientId, NsdManager.FAILURE_BAD_PARAMETERS);
480 }
481 break;
Luke Huang05298582021-06-13 16:52:05 +0000482 case NsdManager.DAEMON_CLEANUP:
paulhu2b9ed952022-02-10 21:58:32 +0800483 maybeStopDaemon();
Luke Huang05298582021-06-13 16:52:05 +0000484 break;
Luke Huangf7277ed2021-07-12 21:15:10 +0800485 // This event should be only sent by the legacy (target SDK < S) clients.
486 // Mark the sending client as legacy.
487 case NsdManager.DAEMON_STARTUP:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900488 cInfo = getClientInfoForReply(msg);
Luke Huangf7277ed2021-07-12 21:15:10 +0800489 if (cInfo != null) {
490 cancelStop();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900491 cInfo.setPreSClient();
Luke Huangf7277ed2021-07-12 21:15:10 +0800492 mLegacyClientCount += 1;
493 maybeStartDaemon();
494 }
495 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700496 default:
paulhub2225702021-11-17 09:35:33 +0800497 Log.e(TAG, "Unhandled " + msg);
Irfan Sheriff75006652012-04-17 23:15:29 -0700498 return NOT_HANDLED;
499 }
500 return HANDLED;
501 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900502
503 private ClientInfo getClientInfoForReply(Message msg) {
504 final ListenerArgs args = (ListenerArgs) msg.obj;
505 return mClients.get(args.connector);
506 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700507 }
508
Irfan Sheriff75006652012-04-17 23:15:29 -0700509 class EnabledState extends State {
510 @Override
511 public void enter() {
512 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700513 }
514
515 @Override
516 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000517 // TODO: it is incorrect to stop the daemon without expunging all requests
518 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000519 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700520 }
521
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700522 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900523 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800524 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700525 return true;
526 }
527 return false;
528 }
529
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900530 private void storeLegacyRequestMap(int clientId, int globalId, ClientInfo clientInfo,
531 int what) {
532 clientInfo.mClientRequests.put(clientId, new LegacyClientRequest(globalId, what));
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700533 mIdToClientInfoMap.put(globalId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000534 // Remove the cleanup event because here comes a new request.
535 cancelStop();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700536 }
537
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900538 private void storeAdvertiserRequestMap(int clientId, int globalId,
Paul Hu23fa2022023-01-13 22:57:24 +0800539 ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900540 clientInfo.mClientRequests.put(clientId, new AdvertiserClientRequest(globalId));
541 mIdToClientInfoMap.put(globalId, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800542 }
543
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900544 private void removeRequestMap(int clientId, int globalId, ClientInfo clientInfo) {
545 final ClientRequest existing = clientInfo.mClientRequests.get(clientId);
546 if (existing == null) return;
547 clientInfo.mClientRequests.remove(clientId);
548 mIdToClientInfoMap.remove(globalId);
549
550 if (existing instanceof LegacyClientRequest) {
551 maybeScheduleStop();
552 } else {
553 maybeStopMonitoringSocketsIfNoActiveRequest();
554 }
555 }
556
557 private void storeDiscoveryManagerRequestMap(int clientId, int globalId,
558 MdnsListener listener, ClientInfo clientInfo) {
559 clientInfo.mClientRequests.put(clientId,
560 new DiscoveryManagerRequest(globalId, listener));
561 mIdToClientInfoMap.put(globalId, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800562 }
563
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900564 /**
565 * Truncate a service name to up to 63 UTF-8 bytes.
566 *
567 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
568 * names used in registerService follows historical behavior (see mdnsresponder
569 * handle_regservice_request).
570 */
571 @NonNull
572 private String truncateServiceName(@NonNull String originalName) {
573 // UTF-8 is at most 4 bytes per character; return early in the common case where
574 // the name can't possibly be over the limit given its string length.
575 if (originalName.length() <= MAX_LABEL_LENGTH / 4) return originalName;
576
577 final Charset utf8 = StandardCharsets.UTF_8;
578 final CharsetEncoder encoder = utf8.newEncoder();
579 final ByteBuffer out = ByteBuffer.allocate(MAX_LABEL_LENGTH);
580 // encode will write as many characters as possible to the out buffer, and just
581 // return an overflow code if there were too many characters (no need to check the
582 // return code here, this method truncates the name on purpose).
583 encoder.encode(CharBuffer.wrap(originalName), out, true /* endOfInput */);
584 return new String(out.array(), 0, out.position(), utf8);
Paul Hu23fa2022023-01-13 22:57:24 +0800585 }
586
Paul Hue4f5f252023-02-16 21:13:47 +0800587 private void stopDiscoveryManagerRequest(ClientRequest request, int clientId, int id,
588 ClientInfo clientInfo) {
589 clientInfo.unregisterMdnsListenerFromRequest(request);
590 removeRequestMap(clientId, id, clientInfo);
591 }
592
Irfan Sheriff75006652012-04-17 23:15:29 -0700593 @Override
594 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900595 final ClientInfo clientInfo;
596 final int id;
597 final int clientId = msg.arg2;
598 final ListenerArgs args;
Irfan Sheriff75006652012-04-17 23:15:29 -0700599 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800600 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800601 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900602 args = (ListenerArgs) msg.obj;
603 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000604 // If the binder death notification for a INsdManagerCallback was received
605 // before any calls are received by NsdService, the clientInfo would be
606 // cleared and cause NPE. Add a null check here to prevent this corner case.
607 if (clientInfo == null) {
608 Log.e(TAG, "Unknown connector in discovery");
609 break;
610 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700611
612 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900613 clientInfo.onDiscoverServicesFailed(
614 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriff75006652012-04-17 23:15:29 -0700615 break;
616 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700617
Paul Hu23fa2022023-01-13 22:57:24 +0800618 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700619 id = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900620 final String serviceType = constructServiceType(info.getServiceType());
Paul Hu2e0a88c2023-03-09 16:05:01 +0800621 if (clientInfo.mUseJavaBackend
622 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900623 || useDiscoveryManagerForType(serviceType)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800624 if (serviceType == null) {
625 clientInfo.onDiscoverServicesFailed(clientId,
626 NsdManager.FAILURE_INTERNAL_ERROR);
627 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700628 }
Paul Hu23fa2022023-01-13 22:57:24 +0800629
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900630 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800631 maybeStartMonitoringSockets();
632 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900633 new DiscoveryListener(clientId, id, info, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800634 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
635 .setNetwork(info.getNetwork())
636 .setIsPassiveMode(true)
637 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900638 mMdnsDiscoveryManager.registerListener(
639 listenServiceType, listener, options);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900640 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800641 clientInfo.onDiscoverServicesStarted(clientId, info);
Paul Hub2e67d32023-04-18 05:50:14 +0000642 clientInfo.log("Register a DiscoveryListener " + id
643 + " for service type:" + listenServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700644 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800645 maybeStartDaemon();
646 if (discoverServices(id, info)) {
647 if (DBG) {
648 Log.d(TAG, "Discover " + msg.arg2 + " " + id
649 + info.getServiceType());
650 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900651 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu23fa2022023-01-13 22:57:24 +0800652 clientInfo.onDiscoverServicesStarted(clientId, info);
653 } else {
654 stopServiceDiscovery(id);
655 clientInfo.onDiscoverServicesFailed(clientId,
656 NsdManager.FAILURE_INTERNAL_ERROR);
657 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700658 }
659 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800660 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900661 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800662 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900663 args = (ListenerArgs) msg.obj;
664 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000665 // If the binder death notification for a INsdManagerCallback was received
666 // before any calls are received by NsdService, the clientInfo would be
667 // cleared and cause NPE. Add a null check here to prevent this corner case.
668 if (clientInfo == null) {
669 Log.e(TAG, "Unknown connector in stop discovery");
670 break;
671 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700672
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900673 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
674 if (request == null) {
675 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700676 break;
677 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900678 id = request.mGlobalId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900679 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
680 // point, so this needs to check the type of the original request to
681 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900682 if (request instanceof DiscoveryManagerRequest) {
Paul Hue4f5f252023-02-16 21:13:47 +0800683 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900684 clientInfo.onStopDiscoverySucceeded(clientId);
Paul Hub2e67d32023-04-18 05:50:14 +0000685 clientInfo.log("Unregister the DiscoveryListener " + id);
Irfan Sheriff75006652012-04-17 23:15:29 -0700686 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800687 removeRequestMap(clientId, id, clientInfo);
688 if (stopServiceDiscovery(id)) {
689 clientInfo.onStopDiscoverySucceeded(clientId);
690 } else {
691 clientInfo.onStopDiscoveryFailed(
692 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
693 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700694 }
695 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900696 }
697 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800698 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900699 args = (ListenerArgs) msg.obj;
700 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000701 // If the binder death notification for a INsdManagerCallback was received
702 // before any calls are received by NsdService, the clientInfo would be
703 // cleared and cause NPE. Add a null check here to prevent this corner case.
704 if (clientInfo == null) {
705 Log.e(TAG, "Unknown connector in registration");
706 break;
707 }
708
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700709 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900710 clientInfo.onRegisterServiceFailed(
711 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700712 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700713 }
714
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700715 id = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900716 final NsdServiceInfo serviceInfo = args.serviceInfo;
717 final String serviceType = serviceInfo.getServiceType();
718 final String registerServiceType = constructServiceType(serviceType);
Paul Hu2e0a88c2023-03-09 16:05:01 +0800719 if (clientInfo.mUseJavaBackend
720 || mDeps.isMdnsAdvertiserEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900721 || useAdvertiserForType(registerServiceType)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900722 if (registerServiceType == null) {
723 Log.e(TAG, "Invalid service type: " + serviceType);
724 clientInfo.onRegisterServiceFailed(clientId,
725 NsdManager.FAILURE_INTERNAL_ERROR);
726 break;
727 }
728 serviceInfo.setServiceType(registerServiceType);
729 serviceInfo.setServiceName(truncateServiceName(
730 serviceInfo.getServiceName()));
731
732 maybeStartMonitoringSockets();
733 mAdvertiser.addService(id, serviceInfo);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900734 storeAdvertiserRequestMap(clientId, id, clientInfo);
Irfan Sheriff75006652012-04-17 23:15:29 -0700735 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900736 maybeStartDaemon();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900737 if (registerService(id, serviceInfo)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900738 if (DBG) Log.d(TAG, "Register " + clientId + " " + id);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900739 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900740 // Return success after mDns reports success
741 } else {
742 unregisterService(id);
743 clientInfo.onRegisterServiceFailed(
744 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
745 }
746
Irfan Sheriff75006652012-04-17 23:15:29 -0700747 }
748 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900749 }
750 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800751 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900752 args = (ListenerArgs) msg.obj;
753 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000754 // If the binder death notification for a INsdManagerCallback was received
755 // before any calls are received by NsdService, the clientInfo would be
756 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900757 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800758 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700759 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700760 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900761 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
762 if (request == null) {
763 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
764 break;
765 }
766 id = request.mGlobalId;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900767 removeRequestMap(clientId, id, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900768
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900769 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
770 // so this needs to check the type of the original request to unregister
771 // instead of looking at the flag value.
772 if (request instanceof AdvertiserClientRequest) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900773 mAdvertiser.removeService(id);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900774 clientInfo.onUnregisterServiceSucceeded(clientId);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700775 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900776 if (unregisterService(id)) {
777 clientInfo.onUnregisterServiceSucceeded(clientId);
778 } else {
779 clientInfo.onUnregisterServiceFailed(
780 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
781 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700782 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700783 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900784 }
Paul Hu75069ed2023-01-14 00:31:09 +0800785 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800786 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900787 args = (ListenerArgs) msg.obj;
788 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000789 // If the binder death notification for a INsdManagerCallback was received
790 // before any calls are received by NsdService, the clientInfo would be
791 // cleared and cause NPE. Add a null check here to prevent this corner case.
792 if (clientInfo == null) {
793 Log.e(TAG, "Unknown connector in resolution");
794 break;
795 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700796
Paul Hu75069ed2023-01-14 00:31:09 +0800797 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700798 id = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900799 final String serviceType = constructServiceType(info.getServiceType());
Paul Hu2e0a88c2023-03-09 16:05:01 +0800800 if (clientInfo.mUseJavaBackend
801 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900802 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800803 if (serviceType == null) {
804 clientInfo.onResolveServiceFailed(clientId,
805 NsdManager.FAILURE_INTERNAL_ERROR);
806 break;
807 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900808 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +0800809
810 maybeStartMonitoringSockets();
811 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900812 new ResolutionListener(clientId, id, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800813 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
814 .setNetwork(info.getNetwork())
815 .setIsPassiveMode(true)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900816 .setResolveInstanceName(info.getServiceName())
Paul Hu75069ed2023-01-14 00:31:09 +0800817 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900818 mMdnsDiscoveryManager.registerListener(
819 resolveServiceType, listener, options);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900820 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Paul Hub2e67d32023-04-18 05:50:14 +0000821 clientInfo.log("Register a ResolutionListener " + id
822 + " for service type:" + resolveServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700823 } else {
Paul Hu75069ed2023-01-14 00:31:09 +0800824 if (clientInfo.mResolvedService != null) {
825 clientInfo.onResolveServiceFailed(
826 clientId, NsdManager.FAILURE_ALREADY_ACTIVE);
827 break;
828 }
829
830 maybeStartDaemon();
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900831 if (resolveService(id, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800832 clientInfo.mResolvedService = new NsdServiceInfo();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900833 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu75069ed2023-01-14 00:31:09 +0800834 } else {
835 clientInfo.onResolveServiceFailed(
836 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
837 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700838 }
839 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800840 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900841 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +0000842 if (DBG) Log.d(TAG, "Stop service resolution");
843 args = (ListenerArgs) msg.obj;
844 clientInfo = mClients.get(args.connector);
845 // If the binder death notification for a INsdManagerCallback was received
846 // before any calls are received by NsdService, the clientInfo would be
847 // cleared and cause NPE. Add a null check here to prevent this corner case.
848 if (clientInfo == null) {
849 Log.e(TAG, "Unknown connector in stop resolution");
850 break;
851 }
852
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900853 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
854 if (request == null) {
855 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
856 break;
857 }
858 id = request.mGlobalId;
Paul Hue4f5f252023-02-16 21:13:47 +0800859 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
860 // point, so this needs to check the type of the original request to
861 // unregister instead of looking at the flag value.
862 if (request instanceof DiscoveryManagerRequest) {
863 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Paul Hub58deb72022-12-26 09:24:42 +0000864 clientInfo.onStopResolutionSucceeded(clientId);
Paul Hub2e67d32023-04-18 05:50:14 +0000865 clientInfo.log("Unregister the ResolutionListener " + id);
Paul Hub58deb72022-12-26 09:24:42 +0000866 } else {
Paul Hue4f5f252023-02-16 21:13:47 +0800867 removeRequestMap(clientId, id, clientInfo);
868 if (stopResolveService(id)) {
869 clientInfo.onStopResolutionSucceeded(clientId);
870 } else {
871 clientInfo.onStopResolutionFailed(
872 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
873 }
874 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +0000875 }
Paul Hub58deb72022-12-26 09:24:42 +0000876 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900877 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000878 case NsdManager.REGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +0000879 if (DBG) Log.d(TAG, "Register a service callback");
880 args = (ListenerArgs) msg.obj;
881 clientInfo = mClients.get(args.connector);
882 // If the binder death notification for a INsdManagerCallback was received
883 // before any calls are received by NsdService, the clientInfo would be
884 // cleared and cause NPE. Add a null check here to prevent this corner case.
885 if (clientInfo == null) {
886 Log.e(TAG, "Unknown connector in callback registration");
887 break;
888 }
889
Paul Hu30bd70d2023-02-07 13:20:56 +0000890 final NsdServiceInfo info = args.serviceInfo;
891 id = getUniqueId();
892 final String serviceType = constructServiceType(info.getServiceType());
893 if (serviceType == null) {
894 clientInfo.onServiceInfoCallbackRegistrationFailed(clientId,
895 NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +0000896 break;
897 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000898 final String resolveServiceType = serviceType + ".local";
Paul Hu18aeccc2022-12-27 08:48:48 +0000899
Paul Hu30bd70d2023-02-07 13:20:56 +0000900 maybeStartMonitoringSockets();
901 final MdnsListener listener =
902 new ServiceInfoListener(clientId, id, info, resolveServiceType);
903 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
904 .setNetwork(info.getNetwork())
905 .setIsPassiveMode(true)
906 .setResolveInstanceName(info.getServiceName())
907 .build();
908 mMdnsDiscoveryManager.registerListener(
909 resolveServiceType, listener, options);
910 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Paul Hub2e67d32023-04-18 05:50:14 +0000911 clientInfo.log("Register a ServiceInfoListener " + id
912 + " for service type:" + resolveServiceType);
Paul Hu18aeccc2022-12-27 08:48:48 +0000913 break;
Paul Hu30bd70d2023-02-07 13:20:56 +0000914 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900915 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +0000916 if (DBG) Log.d(TAG, "Unregister a service callback");
917 args = (ListenerArgs) msg.obj;
918 clientInfo = mClients.get(args.connector);
919 // If the binder death notification for a INsdManagerCallback was received
920 // before any calls are received by NsdService, the clientInfo would be
921 // cleared and cause NPE. Add a null check here to prevent this corner case.
922 if (clientInfo == null) {
923 Log.e(TAG, "Unknown connector in callback unregistration");
924 break;
925 }
926
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900927 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
928 if (request == null) {
Paul Hu30bd70d2023-02-07 13:20:56 +0000929 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE_CALLBACK");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900930 break;
931 }
932 id = request.mGlobalId;
Paul Hu30bd70d2023-02-07 13:20:56 +0000933 if (request instanceof DiscoveryManagerRequest) {
934 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Paul Hu18aeccc2022-12-27 08:48:48 +0000935 clientInfo.onServiceInfoCallbackUnregistered(clientId);
Paul Hub2e67d32023-04-18 05:50:14 +0000936 clientInfo.log("Unregister the ServiceInfoListener " + id);
Paul Hu18aeccc2022-12-27 08:48:48 +0000937 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +0000938 loge("Unregister failed with non-DiscoveryManagerRequest.");
Paul Hu18aeccc2022-12-27 08:48:48 +0000939 }
Paul Hu18aeccc2022-12-27 08:48:48 +0000940 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900941 }
paulhu2b9ed952022-02-10 21:58:32 +0800942 case MDNS_SERVICE_EVENT:
943 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +0900944 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700945 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700946 break;
Paul Hu019621e2023-01-13 23:26:49 +0800947 case MDNS_DISCOVERY_MANAGER_EVENT:
948 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
949 return NOT_HANDLED;
950 }
951 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700952 default:
Hugo Benichif0c84092017-04-05 14:43:29 +0900953 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700954 }
Hugo Benichif0c84092017-04-05 14:43:29 +0900955 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700956 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700957
paulhu2b9ed952022-02-10 21:58:32 +0800958 private boolean handleMDnsServiceEvent(int code, int id, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700959 NsdServiceInfo servInfo;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700960 ClientInfo clientInfo = mIdToClientInfoMap.get(id);
961 if (clientInfo == null) {
paulhu2b9ed952022-02-10 21:58:32 +0800962 Log.e(TAG, String.format("id %d for %d has no client mapping", id, code));
Hugo Benichif0c84092017-04-05 14:43:29 +0900963 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700964 }
965
966 /* This goes in response as msg.arg2 */
Christopher Lane74411222014-04-25 18:39:07 -0700967 int clientId = clientInfo.getClientId(id);
968 if (clientId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -0700969 // This can happen because of race conditions. For example,
970 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
971 // and we may get in this situation.
paulhu2b9ed952022-02-10 21:58:32 +0800972 Log.d(TAG, String.format("%d for listener id %d that is no longer active",
973 code, id));
Hugo Benichif0c84092017-04-05 14:43:29 +0900974 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700975 }
Hugo Benichi32be63d2017-04-05 14:06:11 +0900976 if (DBG) {
paulhu2b9ed952022-02-10 21:58:32 +0800977 Log.d(TAG, String.format("MDns service event code:%d id=%d", code, id));
Hugo Benichi32be63d2017-04-05 14:06:11 +0900978 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700979 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +0800980 case IMDnsEventListener.SERVICE_FOUND: {
981 final DiscoveryInfo info = (DiscoveryInfo) obj;
982 final String name = info.serviceName;
983 final String type = info.registrationType;
984 servInfo = new NsdServiceInfo(name, type);
985 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900986 if (foundNetId == 0L) {
987 // Ignore services that do not have a Network: they are not usable
988 // by apps, as they would need privileged permissions to use
989 // interfaces that do not have an associated Network.
990 break;
991 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +0900992 if (foundNetId == INetd.DUMMY_NET_ID) {
993 // Ignore services on the dummy0 interface: they are only seen when
994 // discovering locally advertised services, and are not reachable
995 // through that interface.
996 break;
997 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900998 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900999 clientInfo.onServiceFound(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001000 break;
paulhu2b9ed952022-02-10 21:58:32 +08001001 }
1002 case IMDnsEventListener.SERVICE_LOST: {
1003 final DiscoveryInfo info = (DiscoveryInfo) obj;
1004 final String name = info.serviceName;
1005 final String type = info.registrationType;
1006 final int lostNetId = info.netId;
1007 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001008 // The network could be set to null (netId 0) if it was torn down when the
1009 // service is lost
1010 // TODO: avoid returning null in that case, possibly by remembering
1011 // found services on the same interface index and their network at the time
1012 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001013 clientInfo.onServiceLost(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001014 break;
paulhu2b9ed952022-02-10 21:58:32 +08001015 }
1016 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001017 clientInfo.onDiscoverServicesFailed(
1018 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001019 break;
paulhu2b9ed952022-02-10 21:58:32 +08001020 case IMDnsEventListener.SERVICE_REGISTERED: {
1021 final RegistrationInfo info = (RegistrationInfo) obj;
1022 final String name = info.serviceName;
1023 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001024 clientInfo.onRegisterServiceSucceeded(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001025 break;
paulhu2b9ed952022-02-10 21:58:32 +08001026 }
1027 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001028 clientInfo.onRegisterServiceFailed(
1029 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001030 break;
paulhu2b9ed952022-02-10 21:58:32 +08001031 case IMDnsEventListener.SERVICE_RESOLVED: {
1032 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001033 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +08001034 final String fullName = info.serviceFullName;
1035 while (index < fullName.length() && fullName.charAt(index) != '.') {
1036 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001037 ++index;
1038 }
1039 ++index;
1040 }
paulhu2b9ed952022-02-10 21:58:32 +08001041 if (index >= fullName.length()) {
1042 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001043 break;
1044 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001045
paulhube186602022-04-12 07:18:23 +00001046 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001047 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001048 String type = rest.replace(".local.", "");
1049
Paul Hu30bd70d2023-02-07 13:20:56 +00001050 final NsdServiceInfo serviceInfo = clientInfo.mResolvedService;
Paul Hu18aeccc2022-12-27 08:48:48 +00001051 serviceInfo.setServiceName(name);
1052 serviceInfo.setServiceType(type);
1053 serviceInfo.setPort(info.port);
1054 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001055 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001056
1057 stopResolveService(id);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001058 removeRequestMap(clientId, id, clientInfo);
1059
paulhu2b9ed952022-02-10 21:58:32 +08001060 final int id2 = getUniqueId();
1061 if (getAddrInfo(id2, info.hostname, info.interfaceIdx)) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001062 storeLegacyRequestMap(clientId, id2, clientInfo,
1063 NsdManager.RESOLVE_SERVICE);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001064 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001065 clientInfo.onResolveServiceFailed(
1066 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1067 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001068 }
1069 break;
paulhu2b9ed952022-02-10 21:58:32 +08001070 }
1071 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001072 /* NNN resolveId errorCode */
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001073 stopResolveService(id);
1074 removeRequestMap(clientId, id, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001075 clientInfo.onResolveServiceFailed(
1076 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1077 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001078 break;
paulhu2b9ed952022-02-10 21:58:32 +08001079 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001080 /* NNN resolveId errorCode */
1081 stopGetAddrInfo(id);
1082 removeRequestMap(clientId, id, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001083 clientInfo.onResolveServiceFailed(
1084 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1085 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001086 break;
paulhu2b9ed952022-02-10 21:58:32 +08001087 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001088 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001089 final GetAddressInfo info = (GetAddressInfo) obj;
1090 final String address = info.address;
1091 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001092 InetAddress serviceHost = null;
1093 try {
paulhu2b9ed952022-02-10 21:58:32 +08001094 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001095 } catch (UnknownHostException e) {
1096 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1097 }
1098
1099 // If the resolved service is on an interface without a network, consider it
1100 // as a failure: it would not be usable by apps as they would need
1101 // privileged permissions.
Paul Hu30bd70d2023-02-07 13:20:56 +00001102 if (netId != NETID_UNSET && serviceHost != null) {
1103 clientInfo.mResolvedService.setHost(serviceHost);
1104 setServiceNetworkForCallback(clientInfo.mResolvedService,
1105 netId, info.interfaceIdx);
1106 clientInfo.onResolveServiceSucceeded(
1107 clientId, clientInfo.mResolvedService);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001108 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001109 clientInfo.onResolveServiceFailed(
1110 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001111 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001112 stopGetAddrInfo(id);
1113 removeRequestMap(clientId, id, clientInfo);
1114 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001115 break;
paulhu2b9ed952022-02-10 21:58:32 +08001116 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001117 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001118 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001119 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001120 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001121 }
Paul Hu019621e2023-01-13 23:26:49 +08001122
1123 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(final MdnsEvent event) {
1124 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1125 final String serviceType = event.mRequestedServiceType;
1126 final String serviceName = serviceInfo.getServiceInstanceName();
1127 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1128 final Network network = serviceInfo.getNetwork();
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001129 // In MdnsDiscoveryManagerEvent, the Network can be null which means it is a
1130 // network for Tethering interface. In other words, the network == null means the
1131 // network has netId = INetd.LOCAL_NET_ID.
Paul Hu019621e2023-01-13 23:26:49 +08001132 setServiceNetworkForCallback(
1133 servInfo,
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001134 network == null ? INetd.LOCAL_NET_ID : network.netId,
Paul Hu019621e2023-01-13 23:26:49 +08001135 serviceInfo.getInterfaceIndex());
1136 return servInfo;
1137 }
1138
1139 private boolean handleMdnsDiscoveryManagerEvent(
1140 int transactionId, int code, Object obj) {
1141 final ClientInfo clientInfo = mIdToClientInfoMap.get(transactionId);
1142 if (clientInfo == null) {
1143 Log.e(TAG, String.format(
1144 "id %d for %d has no client mapping", transactionId, code));
1145 return false;
1146 }
1147
1148 final MdnsEvent event = (MdnsEvent) obj;
1149 final int clientId = event.mClientId;
Paul Hu319751a2023-01-13 23:56:34 +08001150 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event);
Paul Hu019621e2023-01-13 23:26:49 +08001151 if (DBG) {
1152 Log.d(TAG, String.format("MdnsDiscoveryManager event code=%s transactionId=%d",
1153 NsdManager.nameOf(code), transactionId));
1154 }
1155 switch (code) {
1156 case NsdManager.SERVICE_FOUND:
Paul Hu319751a2023-01-13 23:56:34 +08001157 clientInfo.onServiceFound(clientId, info);
1158 break;
1159 case NsdManager.SERVICE_LOST:
1160 clientInfo.onServiceLost(clientId, info);
Paul Hu019621e2023-01-13 23:26:49 +08001161 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001162 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001163 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
1164 if (request == null) {
1165 Log.e(TAG, "Unknown client request in RESOLVE_SERVICE_SUCCEEDED");
1166 break;
1167 }
Paul Hu75069ed2023-01-14 00:31:09 +08001168 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1169 // Add '.' in front of the service type that aligns with historical behavior
1170 info.setServiceType("." + event.mRequestedServiceType);
1171 info.setPort(serviceInfo.getPort());
1172
1173 Map<String, String> attrs = serviceInfo.getAttributes();
1174 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1175 final String key = kv.getKey();
1176 try {
1177 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1178 } catch (IllegalArgumentException e) {
1179 Log.e(TAG, "Invalid attribute", e);
1180 }
1181 }
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001182 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu2b865912023-03-06 14:27:53 +08001183 if (addresses.size() != 0) {
1184 info.setHostAddresses(addresses);
Paul Hu75069ed2023-01-14 00:31:09 +08001185 clientInfo.onResolveServiceSucceeded(clientId, info);
Paul Hu2b865912023-03-06 14:27:53 +08001186 } else {
1187 // No address. Notify resolution failure.
Paul Hu75069ed2023-01-14 00:31:09 +08001188 clientInfo.onResolveServiceFailed(
1189 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1190 }
1191
1192 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001193 if (!(request instanceof DiscoveryManagerRequest)) {
1194 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1195 break;
1196 }
Paul Hue4f5f252023-02-16 21:13:47 +08001197 stopDiscoveryManagerRequest(request, clientId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001198 break;
1199 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001200 case NsdManager.SERVICE_UPDATED: {
1201 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1202 info.setPort(serviceInfo.getPort());
1203
1204 Map<String, String> attrs = serviceInfo.getAttributes();
1205 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1206 final String key = kv.getKey();
1207 try {
1208 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1209 } catch (IllegalArgumentException e) {
1210 Log.e(TAG, "Invalid attribute", e);
1211 }
1212 }
1213
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001214 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001215 info.setHostAddresses(addresses);
1216 clientInfo.onServiceUpdated(clientId, info);
1217 break;
1218 }
1219 case NsdManager.SERVICE_UPDATED_LOST:
1220 clientInfo.onServiceUpdatedLost(clientId);
1221 break;
Paul Hu019621e2023-01-13 23:26:49 +08001222 default:
1223 return false;
1224 }
1225 return true;
1226 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001227 }
1228 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001229
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001230 @NonNull
1231 private static List<InetAddress> getInetAddresses(@NonNull MdnsServiceInfo serviceInfo) {
1232 final List<String> v4Addrs = serviceInfo.getIpv4Addresses();
1233 final List<String> v6Addrs = serviceInfo.getIpv6Addresses();
1234 final List<InetAddress> addresses = new ArrayList<>(v4Addrs.size() + v6Addrs.size());
1235 for (String ipv4Address : v4Addrs) {
1236 try {
1237 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1238 } catch (IllegalArgumentException e) {
1239 Log.wtf(TAG, "Invalid ipv4 address", e);
1240 }
1241 }
1242 for (String ipv6Address : v6Addrs) {
1243 try {
Yuyang Huanga6a6ff92023-04-24 13:33:34 +09001244 final Inet6Address addr = (Inet6Address) InetAddresses.parseNumericAddress(
1245 ipv6Address);
1246 addresses.add(InetAddressUtils.withScopeId(addr, serviceInfo.getInterfaceIndex()));
1247 } catch (IllegalArgumentException e) {
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001248 Log.wtf(TAG, "Invalid ipv6 address", e);
1249 }
1250 }
1251 return addresses;
1252 }
1253
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001254 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1255 switch (netId) {
1256 case NETID_UNSET:
1257 info.setNetwork(null);
1258 break;
1259 case INetd.LOCAL_NET_ID:
1260 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1261 // visible / usable for apps, so do not return it. Store the interface
1262 // index instead, so at least if the client tries to resolve the service
1263 // with that NsdServiceInfo, it will be done on the same interface.
1264 // If they recreate the NsdServiceInfo themselves, resolution would be
1265 // done on all interfaces as before T, which should also work.
1266 info.setNetwork(null);
1267 info.setInterfaceIndex(ifaceIdx);
1268 break;
1269 default:
1270 info.setNetwork(new Network(netId));
1271 }
1272 }
1273
paulhube186602022-04-12 07:18:23 +00001274 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1275 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1276 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1277 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1278 private String unescape(String s) {
1279 StringBuilder sb = new StringBuilder(s.length());
1280 for (int i = 0; i < s.length(); ++i) {
1281 char c = s.charAt(i);
1282 if (c == '\\') {
1283 if (++i >= s.length()) {
1284 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1285 break;
1286 }
1287 c = s.charAt(i);
1288 if (c != '.' && c != '\\') {
1289 if (i + 2 >= s.length()) {
1290 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1291 break;
1292 }
1293 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1294 + (s.charAt(i + 2) - '0'));
1295 i += 2;
1296 }
1297 }
1298 sb.append(c);
1299 }
1300 return sb.toString();
1301 }
1302
Paul Hu7445e3d2023-03-03 15:14:00 +08001303 /**
1304 * Check the given service type is valid and construct it to a service type
1305 * which can use for discovery / resolution service.
1306 *
1307 * <p> The valid service type should be 2 labels, or 3 labels if the query is for a
1308 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1309 * underscore; they are alphanumerical characters or dashes or underscore, except the
1310 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1311 *
1312 * @param serviceType the request service type for discovery / resolution service
1313 * @return constructed service type or null if the given service type is invalid.
1314 */
1315 @Nullable
1316 public static String constructServiceType(String serviceType) {
1317 if (TextUtils.isEmpty(serviceType)) return null;
1318
1319 final Pattern serviceTypePattern = Pattern.compile(
1320 "^(_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]\\.)?"
1321 + "(_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]\\._(?:tcp|udp))"
1322 // Drop '.' at the end of service type that is compatible with old backend.
1323 + "\\.?$");
1324 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1325 if (!matcher.matches()) return null;
1326 return matcher.group(1) == null
1327 ? matcher.group(2)
1328 : matcher.group(1) + "_sub." + matcher.group(2);
1329 }
1330
Hugo Benichi803a2f02017-04-24 11:35:06 +09001331 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001332 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001333 this(ctx, handler, cleanupDelayMs, new Dependencies());
1334 }
1335
1336 @VisibleForTesting
1337 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001338 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001339 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001340 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001341 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001342 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1343 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001344 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001345
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001346 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper());
Yuyang Huang700778b2023-03-08 16:17:05 +09001347 // Netlink monitor starts on boot, and intentionally never stopped, to ensure that all
1348 // address events are received.
1349 handler.post(mMdnsSocketProvider::startNetLinkMonitor);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001350 mMdnsSocketClient =
1351 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider);
1352 mMdnsDiscoveryManager =
1353 deps.makeMdnsDiscoveryManager(new ExecutorProvider(), mMdnsSocketClient);
1354 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1355 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
1356 new AdvertiserCallback());
Paul Hu4bd98ef2023-01-12 13:42:07 +08001357 }
1358
1359 /**
1360 * Dependencies of NsdService, for injection in tests.
1361 */
1362 @VisibleForTesting
1363 public static class Dependencies {
1364 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001365 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001366 *
1367 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001368 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001369 */
1370 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +09001371 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context,
1372 NAMESPACE_CONNECTIVITY, MDNS_DISCOVERY_MANAGER_VERSION,
1373 false /* defaultEnabled */);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001374 }
1375
1376 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001377 * Check whether the MdnsAdvertiser feature is enabled.
1378 *
1379 * @param context The global context information about an app environment.
1380 * @return true if the MdnsAdvertiser feature is enabled.
1381 */
1382 public boolean isMdnsAdvertiserEnabled(Context context) {
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +09001383 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context,
1384 NAMESPACE_CONNECTIVITY, MDNS_ADVERTISER_VERSION, false /* defaultEnabled */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001385 }
1386
1387 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001388 * Get the type allowlist flag value.
1389 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1390 */
1391 @Nullable
1392 public String getTypeAllowlistFlags() {
1393 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1394 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1395 }
1396
1397 /**
1398 * @see DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)
1399 */
1400 public boolean isFeatureEnabled(Context context, String feature) {
1401 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1402 feature, DeviceConfigUtils.TETHERING_MODULE_NAME, false /* defaultEnabled */);
1403 }
1404
1405 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001406 * @see MdnsDiscoveryManager
1407 */
1408 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
1409 ExecutorProvider executorProvider, MdnsSocketClientBase socketClient) {
1410 return new MdnsDiscoveryManager(executorProvider, socketClient);
1411 }
1412
1413 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001414 * @see MdnsAdvertiser
1415 */
1416 public MdnsAdvertiser makeMdnsAdvertiser(
1417 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
1418 @NonNull MdnsAdvertiser.AdvertiserCallback cb) {
1419 return new MdnsAdvertiser(looper, socketProvider, cb);
1420 }
1421
1422 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001423 * @see MdnsSocketProvider
1424 */
1425 public MdnsSocketProvider makeMdnsSocketProvider(Context context, Looper looper) {
1426 return new MdnsSocketProvider(context, looper);
1427 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001428 }
1429
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001430 /**
1431 * Return whether a type is allowlisted to use the Java backend.
1432 * @param type The service type
1433 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1434 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1435 */
1436 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1437 @NonNull String flagPrefix) {
1438 if (type == null) return false;
1439 final String typesConfig = mDeps.getTypeAllowlistFlags();
1440 if (TextUtils.isEmpty(typesConfig)) return false;
1441
1442 final String mappingPrefix = type + ":";
1443 String mappedFlag = null;
1444 for (String mapping : TextUtils.split(typesConfig, ",")) {
1445 if (mapping.startsWith(mappingPrefix)) {
1446 mappedFlag = mapping.substring(mappingPrefix.length());
1447 break;
1448 }
1449 }
1450
1451 if (mappedFlag == null) return false;
1452
1453 return mDeps.isFeatureEnabled(mContext,
1454 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1455 }
1456
1457 private boolean useDiscoveryManagerForType(@Nullable String type) {
1458 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1459 }
1460
1461 private boolean useAdvertiserForType(@Nullable String type) {
1462 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1463 }
1464
paulhu1b35e822022-04-08 14:48:41 +08001465 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001466 HandlerThread thread = new HandlerThread(TAG);
1467 thread.start();
1468 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001469 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001470 return service;
1471 }
1472
paulhu2b9ed952022-02-10 21:58:32 +08001473 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1474 private final StateMachine mStateMachine;
1475
1476 MDnsEventCallback(StateMachine sm) {
1477 mStateMachine = sm;
1478 }
1479
1480 @Override
1481 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1482 mStateMachine.sendMessage(
1483 MDNS_SERVICE_EVENT, status.result, status.id, status);
1484 }
1485
1486 @Override
1487 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1488 mStateMachine.sendMessage(
1489 MDNS_SERVICE_EVENT, status.result, status.id, status);
1490 }
1491
1492 @Override
1493 public void onServiceResolutionStatus(final ResolutionInfo status) {
1494 mStateMachine.sendMessage(
1495 MDNS_SERVICE_EVENT, status.result, status.id, status);
1496 }
1497
1498 @Override
1499 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1500 mStateMachine.sendMessage(
1501 MDNS_SERVICE_EVENT, status.result, status.id, status);
1502 }
1503
1504 @Override
1505 public int getInterfaceVersion() throws RemoteException {
1506 return this.VERSION;
1507 }
1508
1509 @Override
1510 public String getInterfaceHash() throws RemoteException {
1511 return this.HASH;
1512 }
1513 }
1514
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001515 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
1516 @Override
1517 public void onRegisterServiceSucceeded(int serviceId, NsdServiceInfo registeredInfo) {
1518 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1519 if (clientInfo == null) return;
1520
1521 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1522 if (clientId < 0) return;
1523
1524 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1525 // historical behavior.
1526 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
1527 clientInfo.onRegisterServiceSucceeded(clientId, cbInfo);
1528 }
1529
1530 @Override
1531 public void onRegisterServiceFailed(int serviceId, int errorCode) {
1532 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1533 if (clientInfo == null) return;
1534
1535 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1536 if (clientId < 0) return;
1537
1538 clientInfo.onRegisterServiceFailed(clientId, errorCode);
1539 }
1540
1541 private ClientInfo getClientInfoOrLog(int serviceId) {
1542 final ClientInfo clientInfo = mIdToClientInfoMap.get(serviceId);
1543 if (clientInfo == null) {
1544 Log.e(TAG, String.format("Callback for service %d has no client", serviceId));
1545 }
1546 return clientInfo;
1547 }
1548
1549 private int getClientIdOrLog(@NonNull ClientInfo info, int serviceId) {
1550 final int clientId = info.getClientId(serviceId);
1551 if (clientId < 0) {
1552 Log.e(TAG, String.format("Client ID not found for service %d", serviceId));
1553 }
1554 return clientId;
1555 }
1556 }
1557
Paul Hu2e0a88c2023-03-09 16:05:01 +08001558 private static class ConnectorArgs {
1559 @NonNull public final NsdServiceConnector connector;
1560 @NonNull public final INsdManagerCallback callback;
1561 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001562 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001563
1564 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00001565 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08001566 this.connector = connector;
1567 this.callback = callback;
1568 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001569 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001570 }
1571 }
1572
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001573 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08001574 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001575 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu2e0a88c2023-03-09 16:05:01 +08001576 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001577 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00001578 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
1579 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend,
1580 Binder.getCallingUid())));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001581 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07001582 }
1583
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001584 private static class ListenerArgs {
1585 public final NsdServiceConnector connector;
1586 public final NsdServiceInfo serviceInfo;
1587 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
1588 this.connector = connector;
1589 this.serviceInfo = serviceInfo;
1590 }
1591 }
1592
1593 private class NsdServiceConnector extends INsdServiceConnector.Stub
1594 implements IBinder.DeathRecipient {
1595 @Override
1596 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
1597 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1598 NsdManager.REGISTER_SERVICE, 0, listenerKey,
1599 new ListenerArgs(this, serviceInfo)));
1600 }
1601
1602 @Override
1603 public void unregisterService(int listenerKey) {
1604 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1605 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
1606 new ListenerArgs(this, null)));
1607 }
1608
1609 @Override
1610 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
1611 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1612 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
1613 new ListenerArgs(this, serviceInfo)));
1614 }
1615
1616 @Override
1617 public void stopDiscovery(int listenerKey) {
1618 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1619 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
1620 }
1621
1622 @Override
1623 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
1624 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1625 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
1626 new ListenerArgs(this, serviceInfo)));
1627 }
1628
1629 @Override
Paul Hub58deb72022-12-26 09:24:42 +00001630 public void stopResolution(int listenerKey) {
1631 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1632 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
1633 }
1634
1635 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00001636 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
1637 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1638 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
1639 new ListenerArgs(this, serviceInfo)));
1640 }
1641
1642 @Override
1643 public void unregisterServiceInfoCallback(int listenerKey) {
1644 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1645 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
1646 new ListenerArgs(this, null)));
1647 }
1648
1649 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001650 public void startDaemon() {
1651 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1652 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
1653 }
1654
1655 @Override
1656 public void binderDied() {
1657 mNsdStateMachine.sendMessage(
1658 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
1659 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001660 }
1661
Hugo Benichi912db992017-04-24 16:41:03 +09001662 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07001663 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07001664 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09001665 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
1666 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07001667 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07001668 }
1669
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001670 private int getUniqueId() {
1671 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
1672 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001673 }
1674
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001675 private boolean registerService(int regId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09001676 if (DBG) {
paulhub2225702021-11-17 09:35:33 +08001677 Log.d(TAG, "registerService: " + regId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001678 }
Hugo Benichi6d706442017-04-24 16:19:58 +09001679 String name = service.getServiceName();
1680 String type = service.getServiceType();
1681 int port = service.getPort();
1682 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001683 final int registerInterface = getNetworkInterfaceIndex(service);
1684 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08001685 Log.e(TAG, "Interface to register service on not found");
1686 return false;
1687 }
1688 return mMDnsManager.registerService(regId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001689 }
1690
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001691 private boolean unregisterService(int regId) {
paulhu2b9ed952022-02-10 21:58:32 +08001692 return mMDnsManager.stopOperation(regId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001693 }
1694
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001695 private boolean discoverServices(int discoveryId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08001696 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001697 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
1698 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001699 Log.e(TAG, "Interface to discover service on not found");
1700 return false;
1701 }
paulhu2b9ed952022-02-10 21:58:32 +08001702 return mMDnsManager.discover(discoveryId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001703 }
1704
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001705 private boolean stopServiceDiscovery(int discoveryId) {
paulhu2b9ed952022-02-10 21:58:32 +08001706 return mMDnsManager.stopOperation(discoveryId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001707 }
1708
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001709 private boolean resolveService(int resolveId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001710 final String name = service.getServiceName();
1711 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001712 final int resolveInterface = getNetworkInterfaceIndex(service);
1713 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001714 Log.e(TAG, "Interface to resolve service on not found");
1715 return false;
1716 }
paulhu2b9ed952022-02-10 21:58:32 +08001717 return mMDnsManager.resolve(resolveId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001718 }
1719
1720 /**
1721 * Guess the interface to use to resolve or discover a service on a specific network.
1722 *
1723 * This is an imperfect guess, as for example the network may be gone or not yet fully
1724 * registered. This is fine as failing is correct if the network is gone, and a client
1725 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
1726 * this is to support the legacy mdnsresponder implementation, which historically resolved
1727 * services on an unspecified network.
1728 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001729 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
1730 final Network network = serviceInfo.getNetwork();
1731 if (network == null) {
1732 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
1733 // provided by NsdService from discovery results, and the service was found on an
1734 // interface that has no app-usable Network).
1735 if (serviceInfo.getInterfaceIndex() != 0) {
1736 return serviceInfo.getInterfaceIndex();
1737 }
1738 return IFACE_IDX_ANY;
1739 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001740
1741 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
1742 if (cm == null) {
1743 Log.wtf(TAG, "No ConnectivityManager for resolveService");
1744 return IFACE_IDX_ANY;
1745 }
1746 final LinkProperties lp = cm.getLinkProperties(network);
1747 if (lp == null) return IFACE_IDX_ANY;
1748
1749 // Only resolve on non-stacked interfaces
1750 final NetworkInterface iface;
1751 try {
1752 iface = NetworkInterface.getByName(lp.getInterfaceName());
1753 } catch (SocketException e) {
1754 Log.e(TAG, "Error querying interface", e);
1755 return IFACE_IDX_ANY;
1756 }
1757
1758 if (iface == null) {
1759 Log.e(TAG, "Interface not found: " + lp.getInterfaceName());
1760 return IFACE_IDX_ANY;
1761 }
1762
1763 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001764 }
1765
1766 private boolean stopResolveService(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001767 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001768 }
1769
paulhu2b9ed952022-02-10 21:58:32 +08001770 private boolean getAddrInfo(int resolveId, String hostname, int interfaceIdx) {
1771 return mMDnsManager.getServiceAddress(resolveId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001772 }
1773
1774 private boolean stopGetAddrInfo(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001775 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001776 }
1777
1778 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00001779 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1780 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001781
Paul Hub2e67d32023-04-18 05:50:14 +00001782 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
1783 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07001784 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00001785
1786 // Dump service and clients logs
1787 pw.println();
1788 pw.increaseIndent();
1789 mServiceLogs.reverseDump(pw);
1790 pw.decreaseIndent();
1791
1792 // Dump advertiser related logs
1793 pw.println();
1794 pw.println("Advertiser:");
1795 pw.increaseIndent();
1796 mAdvertiser.dump(pw);
1797 pw.decreaseIndent();
1798
1799 // Dump discoverymanager related logs
1800 pw.println();
1801 pw.println("DiscoveryManager:");
1802 pw.increaseIndent();
1803 mMdnsDiscoveryManager.dump(pw);
1804 pw.decreaseIndent();
1805
1806 // Dump socketprovider related logs
1807 pw.println();
1808 pw.println("SocketProvider:");
1809 pw.increaseIndent();
1810 mMdnsSocketProvider.dump(pw);
1811 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001812 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001813
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001814 private abstract static class ClientRequest {
1815 private final int mGlobalId;
1816
1817 private ClientRequest(int globalId) {
1818 mGlobalId = globalId;
1819 }
1820 }
1821
1822 private static class LegacyClientRequest extends ClientRequest {
1823 private final int mRequestCode;
1824
1825 private LegacyClientRequest(int globalId, int requestCode) {
1826 super(globalId);
1827 mRequestCode = requestCode;
1828 }
1829 }
1830
1831 private static class AdvertiserClientRequest extends ClientRequest {
1832 private AdvertiserClientRequest(int globalId) {
1833 super(globalId);
1834 }
1835 }
1836
1837 private static class DiscoveryManagerRequest extends ClientRequest {
1838 @NonNull
1839 private final MdnsListener mListener;
1840
1841 private DiscoveryManagerRequest(int globalId, @NonNull MdnsListener listener) {
1842 super(globalId);
1843 mListener = listener;
1844 }
1845 }
1846
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001847 /* Information tracked per client */
1848 private class ClientInfo {
1849
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001850 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001851 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001852 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001853 private NsdServiceInfo mResolvedService;
1854
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001855 /* A map from client-side ID (listenerKey) to the request */
1856 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08001857
Luke Huangf7277ed2021-07-12 21:15:10 +08001858 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001859 private boolean mIsPreSClient = false;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001860 // The flag of using java backend if the client's target SDK >= U
1861 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001862 // Store client logs
1863 private final SharedLog mClientLogs;
Luke Huangf7277ed2021-07-12 21:15:10 +08001864
Paul Hub2e67d32023-04-18 05:50:14 +00001865 private ClientInfo(INsdManagerCallback cb, boolean useJavaBackend, SharedLog sharedLog) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001866 mCb = cb;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001867 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001868 mClientLogs = sharedLog;
1869 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001870 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001871
1872 @Override
1873 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06001874 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07001875 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001876 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
1877 for (int i = 0; i < mClientRequests.size(); i++) {
1878 int clientID = mClientRequests.keyAt(i);
1879 sb.append("clientId ")
1880 .append(clientID)
1881 .append(" mDnsId ").append(mClientRequests.valueAt(i).mGlobalId)
1882 .append(" type ").append(
1883 mClientRequests.valueAt(i).getClass().getSimpleName())
1884 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07001885 }
1886 return sb.toString();
1887 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001888
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001889 private boolean isPreSClient() {
1890 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08001891 }
1892
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001893 private void setPreSClient() {
1894 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08001895 }
1896
Paul Hue4f5f252023-02-16 21:13:47 +08001897 private void unregisterMdnsListenerFromRequest(ClientRequest request) {
1898 final MdnsListener listener =
1899 ((DiscoveryManagerRequest) request).mListener;
1900 mMdnsDiscoveryManager.unregisterListener(
1901 listener.getListenedServiceType(), listener);
1902 }
1903
Dave Plattfeff2af2014-03-07 14:48:22 -08001904 // Remove any pending requests from the global map when we get rid of a client,
1905 // and send cancellations to the daemon.
1906 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00001907 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09001908 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001909 for (int i = 0; i < mClientRequests.size(); i++) {
1910 final int clientId = mClientRequests.keyAt(i);
1911 final ClientRequest request = mClientRequests.valueAt(i);
1912 final int globalId = request.mGlobalId;
Dave Plattfeff2af2014-03-07 14:48:22 -08001913 mIdToClientInfoMap.remove(globalId);
paulhub2225702021-11-17 09:35:33 +08001914 if (DBG) {
1915 Log.d(TAG, "Terminating client-ID " + clientId
1916 + " global-ID " + globalId + " type " + mClientRequests.get(clientId));
1917 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001918
1919 if (request instanceof DiscoveryManagerRequest) {
Paul Hue4f5f252023-02-16 21:13:47 +08001920 unregisterMdnsListenerFromRequest(request);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001921 continue;
1922 }
1923
1924 if (request instanceof AdvertiserClientRequest) {
1925 mAdvertiser.removeService(globalId);
1926 continue;
1927 }
1928
1929 if (!(request instanceof LegacyClientRequest)) {
1930 throw new IllegalStateException("Unknown request type: " + request.getClass());
1931 }
1932
1933 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08001934 case NsdManager.DISCOVER_SERVICES:
1935 stopServiceDiscovery(globalId);
1936 break;
1937 case NsdManager.RESOLVE_SERVICE:
1938 stopResolveService(globalId);
1939 break;
1940 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001941 unregisterService(globalId);
Dave Plattfeff2af2014-03-07 14:48:22 -08001942 break;
1943 default:
1944 break;
1945 }
1946 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001947 mClientRequests.clear();
1948 }
1949
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001950 // mClientRequests is a sparse array of listener id -> ClientRequest. For a given
1951 // mDnsClient id, return the corresponding listener id. mDnsClient id is also called a
1952 // global id.
Christopher Lane74411222014-04-25 18:39:07 -07001953 private int getClientId(final int globalId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001954 for (int i = 0; i < mClientRequests.size(); i++) {
1955 if (mClientRequests.valueAt(i).mGlobalId == globalId) {
1956 return mClientRequests.keyAt(i);
1957 }
Christopher Lane74411222014-04-25 18:39:07 -07001958 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001959 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07001960 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001961
Paul Hub2e67d32023-04-18 05:50:14 +00001962 private void log(String message) {
1963 mClientLogs.log(message);
1964 }
1965
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001966 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info) {
1967 try {
1968 mCb.onDiscoverServicesStarted(listenerKey, info);
1969 } catch (RemoteException e) {
1970 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
1971 }
1972 }
1973
1974 void onDiscoverServicesFailed(int listenerKey, int error) {
1975 try {
1976 mCb.onDiscoverServicesFailed(listenerKey, error);
1977 } catch (RemoteException e) {
1978 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
1979 }
1980 }
1981
1982 void onServiceFound(int listenerKey, NsdServiceInfo info) {
1983 try {
1984 mCb.onServiceFound(listenerKey, info);
1985 } catch (RemoteException e) {
1986 Log.e(TAG, "Error calling onServiceFound(", e);
1987 }
1988 }
1989
1990 void onServiceLost(int listenerKey, NsdServiceInfo info) {
1991 try {
1992 mCb.onServiceLost(listenerKey, info);
1993 } catch (RemoteException e) {
1994 Log.e(TAG, "Error calling onServiceLost(", e);
1995 }
1996 }
1997
1998 void onStopDiscoveryFailed(int listenerKey, int error) {
1999 try {
2000 mCb.onStopDiscoveryFailed(listenerKey, error);
2001 } catch (RemoteException e) {
2002 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
2003 }
2004 }
2005
2006 void onStopDiscoverySucceeded(int listenerKey) {
2007 try {
2008 mCb.onStopDiscoverySucceeded(listenerKey);
2009 } catch (RemoteException e) {
2010 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2011 }
2012 }
2013
2014 void onRegisterServiceFailed(int listenerKey, int error) {
2015 try {
2016 mCb.onRegisterServiceFailed(listenerKey, error);
2017 } catch (RemoteException e) {
2018 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2019 }
2020 }
2021
2022 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info) {
2023 try {
2024 mCb.onRegisterServiceSucceeded(listenerKey, info);
2025 } catch (RemoteException e) {
2026 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2027 }
2028 }
2029
2030 void onUnregisterServiceFailed(int listenerKey, int error) {
2031 try {
2032 mCb.onUnregisterServiceFailed(listenerKey, error);
2033 } catch (RemoteException e) {
2034 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2035 }
2036 }
2037
2038 void onUnregisterServiceSucceeded(int listenerKey) {
2039 try {
2040 mCb.onUnregisterServiceSucceeded(listenerKey);
2041 } catch (RemoteException e) {
2042 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2043 }
2044 }
2045
2046 void onResolveServiceFailed(int listenerKey, int error) {
2047 try {
2048 mCb.onResolveServiceFailed(listenerKey, error);
2049 } catch (RemoteException e) {
2050 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2051 }
2052 }
2053
2054 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info) {
2055 try {
2056 mCb.onResolveServiceSucceeded(listenerKey, info);
2057 } catch (RemoteException e) {
2058 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2059 }
2060 }
Paul Hub58deb72022-12-26 09:24:42 +00002061
2062 void onStopResolutionFailed(int listenerKey, int error) {
2063 try {
2064 mCb.onStopResolutionFailed(listenerKey, error);
2065 } catch (RemoteException e) {
2066 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2067 }
2068 }
2069
2070 void onStopResolutionSucceeded(int listenerKey) {
2071 try {
2072 mCb.onStopResolutionSucceeded(listenerKey);
2073 } catch (RemoteException e) {
2074 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2075 }
2076 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002077
2078 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
2079 try {
2080 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2081 } catch (RemoteException e) {
2082 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2083 }
2084 }
2085
2086 void onServiceUpdated(int listenerKey, NsdServiceInfo info) {
2087 try {
2088 mCb.onServiceUpdated(listenerKey, info);
2089 } catch (RemoteException e) {
2090 Log.e(TAG, "Error calling onServiceUpdated", e);
2091 }
2092 }
2093
2094 void onServiceUpdatedLost(int listenerKey) {
2095 try {
2096 mCb.onServiceUpdatedLost(listenerKey);
2097 } catch (RemoteException e) {
2098 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2099 }
2100 }
2101
2102 void onServiceInfoCallbackUnregistered(int listenerKey) {
2103 try {
2104 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2105 } catch (RemoteException e) {
2106 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2107 }
2108 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002109 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002110}